看板 java 關於我們 聯絡資訊
public class Test extends Thread { char name; Test(char a) { name = a; } public synchronized void run() { for (int i=0; i<3; i++) { System.out.print(name); } } public static void main(String[] args) { new Test('A').start(); new Test('B').start(); new Test('C').start(); } } synchronized的作用不是讓同時間只能一個thread執行method嗎? 因此某個thread進入run()執行後 for迴圈三次應該要跑完才會被其他thread搶到執行權嗎? 想請問為何run()加了synchronized 還是會得到 AACCCBBBA 這樣的輸出 先謝謝各位的解答了~ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.218.53.221 ※ 文章網址: https://www.ptt.cc/bbs/java/M.1448271196.A.B38.html
ssccg: 非static method是對各instance lock,不同instance分開的 11/23 17:37
cha122977: 實際上3個run會被視為不同function 11/23 18:50
LoserOfLove: 謝樓上的回答,那麼我要如何在一個instance開三個 11/23 20:42
LoserOfLove: thread跑run()呢? 11/23 20:43
cha122977: 在run裡面呼叫同一instance的function就可以了 11/23 21:06
ssccg: 如果你這段需要對同class所有instance同步,可以直接 11/23 23:32
ssccg: synchronized (Test.class) { } 包住那段,或是獨立出來成 11/23 23:33
ssccg: static synchronized method 11/23 23:35
ssccg: 如果是要在多個Thread跑同一個instance的run,那這個class 11/23 23:36
ssccg: 不要繼承Thread,實作Runnable再傳進new Thread()就好 11/23 23:37
LoserOfLove: 了解了,謝謝兩位的幫忙~ 11/24 00:53
n3oanderson: http://goo.gl/04o8Z5 11/24 12:52