2
創建的兩個線程誰能告訴我爲什麼synchronized關鍵字不起作用。無法同步在主要()
package Threading;
class NewThreadt extends Thread {
synchronized void dota(int a){
System.out.println(a);
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
dota(i) ;
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
System.out.println(Thread.currentThread());
}
}
class abc {
public static void main(String args[]) {
NewThreadt t=new NewThreadt();
NewThreadt q=new NewThreadt();
t.start();
q.start();
System.out.println("Main thread exiting.");
}
}
輸出我對上述程序執行得到:
5
5
4
4
3
3
2
2
1
1
,我想輸出:
5
4
3
2
1
5
4
3
2
1
標記的'DOTA()'方法如'synchronized'僅確保每次調用'DOTA()'塊的任何其他呼叫''NewThreadt'的同一個實例上的'dota()'。它不會遠程執行您認爲它所做的事情。 – khelwood
爲什麼你使用線程,如果你想完全相應地? -_- – Suvitruf
對包含完整的測試程序以說明問題的一個問題,其實際產出的樣本以及對預期產出的明確說明,恭喜並獲得滿意答覆。這種組合出奇的罕見。 –