Alb*_*ish 1 java concurrency volatile
好的,我只是读了这个问题您是否曾在Java中使用volatile关键字?,我使用volatile变量来停止循环.我也看过这个参考资料,http://www.javamex.com/tutorials/synchronization_volatile.shtml.现在文章说波动变量是非阻塞的.它还说它不能用于读取 - 更新 - 写入序列中的并发.这是有道理的,因为它们是非阻塞的.
因为从不缓存volatile变量,所以简单地使用同步来停止循环(来自早期链接)会更快吗?
编辑:使用同步解决方案
public class A{
private boolean test;
public A(){
test = true;
}
public synchronized void stop(){
test = false;
}
public synchronized boolean isTrue(){
return test;
}
}
public class B extends Thread {
private A a;
public B(A refA){
a = refA;
}
public void run(){
//Does stuff here
try{
sleep(1000);
}
catch(Exception e){}
a.stop();
}
public static void main(String [] args){
A TestA = new A();
B TestB = new B(TestA);
TestB.start();
while(TestA.isTrue()){
//stay in loop
System.out.println("still in loop");
}
System.out.println("Done with loop");
}
}
Run Code Online (Sandbox Code Playgroud)
不,读取volatile变量比读取块中的非volatile变量更快synchronized.
阿synchronized块将清除条目,其是相同的读取高速缓存的值volatile的变量.但是,当退出同步块时,它还会刷新对主内存的任何缓存写入,这在读取volatile变量时不是必需的.