msk*_*sk 3 java concurrency multithreading volatile
在变量上使用volatile可以降低内存一致性错误的风险(如果这揭示了我对任何相关概念的理解中的一些漏洞,请纠正我).因此,在下面的示例中,即使变量c1是易失性的,仍然发生内存持续性错误导致c1在输出中变为15或有时为14而不是正确的输出16.
class Lunch implements Runnable {
private volatile long c1 = 0;
private Object lock1 = new Object();
private Object lock2 = new Object();
public void inc1() {
// synchronized(lock1) { c1 is volatile
c1++;
// }
}
public void run() {
try {
inc1();
Thread.sleep(1000);
inc1();
Thread.sleep(1000);
inc1();
Thread.sleep(1000);
inc1();
inc1();
Thread.sleep(1000);
inc1();
Thread.sleep(1000);
inc1();
Thread.sleep(1000);
inc1();
}
catch(InterruptedException e) {
return;
}
}
public long value() {
return c1;
}
public static void main(String args[]) throws InterruptedException {
Lunch l = new Lunch();
Thread t1 = new Thread(l);
Thread t2 = new Thread(l);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(l.value());
}
}
Run Code Online (Sandbox Code Playgroud)