我正在尝试理解volatile在java中是如何工作的。下面是我尝试过的简单程序
public class ThreadTryTry extends Thread {
static InstanceClass iCLass = null;
public static void main(String args[]) throws InterruptedException {
ThreadTryTry tt1 = new ThreadTryTry();
ThreadTryTry tt2 = new ThreadTryTry();
tt1.setName("thread 1");
tt2.setName("thread 2");
iCLass = new InstanceClass();
tt1.start();
// Thread.sleep(1000);
tt2.start();
// Thread.sleep(1000);
iCLass.display();
}
public void run() {
System.out.println("x= " + iCLass.x + " " + Thread.currentThread().getName());
System.out.println("y= " + iCLass.y + " " + Thread.currentThread().getName());
iCLass.x++;
iCLass.y++;
}
}
class InstanceClass {
volatile int x = 0;
volatile int y = 0;
public void display() {
System.out.println("x= " + x + " y= " + y);
}
}
输出结果与预期一致
x= 0 thread 1
y= 0 thread 1
x= 1 thread 2
y= 1 thread 2
x= 2 y= 2
如果我删除睡眠语句,我会得到如下的随机输出
x= 0 y= 0
x= 0 thread 2
y= 0 thread 2
x= 0 thread 1
y= 1 thread 1
我的期望是,无论线程是否休眠,输出都应该与初始输出相同。
我已经检查了有关易失性的其他问题,但找不到我的程序有什么问题。易失性不能保证变量会被读写回内存,其他线程应该看到变量的最新值。
发布于 2015-07-27 22:29:34
这里没有问题。
可能会发生什么?
在绝对(和假的)时间线上可能的执行:
t1 starts
t2 starts
main displays
t2 prints x=0
t2 prints y=0
t1 prints x=0
t2 increments x
t2 increments y
t1 prints y=1
main、t1和t2之间没有发生关系,因为它们都是并发的,所以发生的顺序可能会有所不同。
https://stackoverflow.com/questions/31655649
复制相似问题