我正在阅读Java中的volatile关键字并完全理解它的理论部分.
但是,我正在寻找的是一个很好的案例,它展示了如果变量不是易变的话会发生什么.
下面的代码片段无法正常工作(来自aioobe)
class Test extends Thread {
boolean keepRunning = true;
public void run() {
while (keepRunning) {
}
System.out.println("Thread terminated.");
}
public static void main(String[] args) throws InterruptedException {
Test t = new Test();
t.start();
Thread.sleep(1000);
t.keepRunning = false;
System.out.println("keepRunning set to false.");
}
}
Run Code Online (Sandbox Code Playgroud)
理想情况下,如果keepRunning不是volatile,则线程应该继续无限运行.但是,它会在几秒钟后停止.
我有两个基本问题: -
以下是经典Concurency in Practice:
当线程A写入volatile变量并且随后线程B读取相同的变量时,在写入volatile变量之前A可见的所有变量的值在读取volatile变量后变为B可见.
我不确定我是否真的能理解这句话.例如,在这种情况下所有变量的含义是什么?这是否意味着使用volatile也会对非易失性变量的使用产生副作用?
在我看来,这句话有一些我无法理解的微妙含义.
有帮助吗?
我已经读过Java中的"volatile"允许不同的线程访问同一个字段并查看其他线程对该字段所做的更改.如果是这种情况,我预测当第一个和第二个线程完全运行时,"d"的值将增加到4.但是,每个线程将"d"增加到值2.
public class VolatileExample extends Thread {
private int countDown = 2;
private volatile int d = 0;
public VolatileExample(String name) {
super(name);
start();
}
public String toString() {
return super.getName() + ": countDown " + countDown;
}
public void run() {
while(true) {
d = d + 1;
System.out.println(this + ". Value of d is " + d);
if(--countDown == 0) return;
}
}
public static void main(String[] args) {
new VolatileExample("first thread");
new VolatileExample("second thread");
}
}
Run Code Online (Sandbox Code Playgroud)
运行此程序的结果是: …