4
我在理解同步關鍵字功能時遇到了一些麻煩。 根據java文檔和其他教程,有人說,當使用synchronized關鍵字時,兩個線程之間不可能在該方法的語句之間交織。執行同步語句執行交錯執行
但是,請參閱下面的一段代碼。
public class LockThread implements Runnable {
String name;
public LockThread(String name) {
this.name = name;
}
public static void main(String[] args) {
new Thread(new LockThread("a")).start();
new Thread(new LockThread("b")).start();
}
public void run() {
locked(Thread.currentThread().getId());
}
synchronized void locked(long l) {
System.out.println(name+"-"+l + "---> Printed from " + Thread.currentThread().getName());
System.out.println(name+"-"+l + "---> Printed from " + Thread.currentThread().getName());
}
}
按我的理解,節目輸出應始終以一種線程0和線程1不應交錯.. 但執行這段代碼多次,我得到一個交錯輸出..
With interleaving (Output I expect) a-9 ---> Printed from Thread-0 a-9 ---> Printed from Thread-0 b-10 ---> Printed from Thread-1 b-10 ---> Printed from Thread-1 Without Interleaving (This is one another output I see for the same code above) a-9 ---> Printed from Thread-0 b-10 ---> Printed from Thread-1 a-9 ---> Printed from Thread-0 b-10 ---> Printed from Thread-1
請幫助我理解這個問題..提前
謝謝..
您需要使用通用鎖 - 例如,您可以使該方法爲靜態,並且您將獲得預期的輸出。 – assylias