[問題] 關於synchronized

看板java作者 (LOL)時間10年前 (2015/11/23 17:33), 編輯推噓0(0012)
留言12則, 4人參與, 最新討論串2/2 (看更多)
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

11/23 17:37, , 1F
非static method是對各instance lock,不同instance分開的
11/23 17:37, 1F

11/23 18:50, , 2F
實際上3個run會被視為不同function
11/23 18:50, 2F

11/23 20:42, , 3F
謝樓上的回答,那麼我要如何在一個instance開三個
11/23 20:42, 3F

11/23 20:43, , 4F
thread跑run()呢?
11/23 20:43, 4F

11/23 21:06, , 5F
在run裡面呼叫同一instance的function就可以了
11/23 21:06, 5F

11/23 23:32, , 6F
如果你這段需要對同class所有instance同步,可以直接
11/23 23:32, 6F

11/23 23:33, , 7F
synchronized (Test.class) { } 包住那段,或是獨立出來成
11/23 23:33, 7F

11/23 23:35, , 8F
static synchronized method
11/23 23:35, 8F

11/23 23:36, , 9F
如果是要在多個Thread跑同一個instance的run,那這個class
11/23 23:36, 9F

11/23 23:37, , 10F
不要繼承Thread,實作Runnable再傳進new Thread()就好
11/23 23:37, 10F

11/24 00:53, , 11F
了解了,謝謝兩位的幫忙~
11/24 00:53, 11F

11/24 12:52, , 12F
11/24 12:52, 12F
文章代碼(AID): #1MKjrSiu (java)
文章代碼(AID): #1MKjrSiu (java)