假设我有两个线程 t1 和 t2 正在尝试访问 incX()
下面是我的代码:
class Test implements Runnable {
private int x = 0;
public void incX() {
synchronized(this) {
x = ++x;
}
System.out.println("x is: "+x+" "+Thread.currentThread().getName());
}
public void run() {
incX();
}
public static void main(String[] args) {
Thread t1 = new Thread(new Test());
t1.start();
Thread t2 = new Thread(new Test());
t2.start();
}
这是我的输出:
x is: 1 Thread-1
x is: 1 Thread-0
在 incX() 方法中,我已经同步了 x =++x,所以对线程 t1 所做的更改应该是可见的线程t2,对吗?所以我的输出应该是:
x is: 1 Thread-1
x is: 2 Thread-0
我知道 ++x 不是原子操作,但它是同步的,所以线程 t2 无法获取锁。所以线程不应该交错并且对x所做的更改应该对线程t2可见,对吗?我误会了吗?
所以我的问题是为什么我没有得到输出:
x is: 2 Thread-0
最佳答案
您正在使用 Test 类的两个独立实例,因此每个实例中的 x 自然只会递增一次。它实际上与此相同:
Test test1 = new Test();
Test test2 = new Test();
test1.incX();
test2.incX();
由于 Test 的每个实例都有自己的 x,您也会看到 1 两次以及该代码。
要测试对相同 实例的同步访问,您需要改用单个实例。例如:
class Test {
private int x = 0;
public void incX() {
synchronized(this) {
x = ++x; // See "Side Note" below
}
System.out.println("x is: "+x+" "+Thread.currentThread().getName());
}
}
public class Main {
public static void main(String[] args) {
Test test = new Test(); // One instance
Thread t1 = new Thread(() -> {
test.incX(); // Used by this thread
});
Thread t2 = new Thread(() -> {
test.incX(); // And also by this one
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
}
catch (Exception e) {
}
System.out.println("Done");
}
}
哪个会输出
x is: 1 Thread-0 x is: 2 Thread-1 Done
or similar (naturally it varies depending on which thread gets scheduled when).
Sometimes, it'll even look like this:
x is: 2 Thread-0 x is: 2 Thread-1 Done
That's because the access to x in the System.out.println statement is outside the synchronized block, so sometimes (not always) x will get incremented after the end of the synchronized block and before the println:
synchronized(this) {
x = ++x;
}
// ***The other thread can jump in here and increment x
System.out.println("x is: "+x+" "+Thread.currentThread().getName());
更详细:
t1进入同步块(synchronized block)t2 尝试进入同步块(synchronized block)但必须等待,因为 t1 有锁t1 递增 x,使其成为 1t1 退出同步块(synchronized block)t2 跳入并递增 x,使其成为 2t2 退出同步块(synchronized block)t1 输出 x (2) 的当前值t2 输出 x (2) 的当前值请注意,第 2 步和第 3 步可以按任何顺序排列,第 6-8 步也可以按任何顺序排列。
为了可靠地报告 x 在递增后在同步块(synchronized block)中的情况,我们想要:
将println移入同步块(synchronized block)
public void incX() {
synchronized(this) {
x = ++x; // See "Side Note" below
System.out.println("x is: "+x+" "+Thread.currentThread().getName());
}
}
或
将自增的结果保存在局部变量中
public void incX() {
int y; // Local variable
synchronized(this) {
y = ++x; // No longer and odd thing to do
}
System.out.println("x is: "+y+" "+Thread.currentThread().getName());
}
除非你有一个非常非常好的理由在输出期间持有同步锁,否则请使用#2。
旁注:正如我在评论中提到的,++x 已经 将其值写回到 x,这就是增量运算符做。所以 x = 的一部分
x = ++x;
...没有必要。要么使用增量运算符:
++x;
...或者不:
x += 1;
关于java - 为什么变量在同步时对其他线程不可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39901528/
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返
我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击
我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是
它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput
我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象