好吧,我只是讀了這個問題Do you ever use the volatile keyword in Java?,我得到了一個volatile變量來停止循環。我也見過這個參考,http://www.javamex.com/tutorials/synchronization_volatile.shtml。現在文章說volatile變量是非阻塞的。並且它表示它不能用於讀取更新寫入序列中的併發。這是有道理的,因爲它們是非阻塞的。Java對於併發性而言是易失性的
由於易失性變量永遠不會被緩存,因此簡單地使用同步來停止循環(從前面的鏈接)會更快嗎?
編輯:使用一個同步的溶液
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");
}
}
你在說什麼循環?請在這個問題中包含一個你建議使用'synchronized'的例子。 – erickson 2010-08-19 18:10:27
轉到我發佈的第一個鏈接,尋找最高評分的答案。 – Albinoswordfish 2010-08-19 18:24:20
你期待着很多讀者。下一次,只是在問題中包含示例... – 2010-08-19 18:34:44