public class Ques0308 implements Runnable {
private String str1 = "this ";
private int[] str2 = {1,2,3,4,5};
public static void main(String[] args) {
Ques0308 test = new Ques0308();
new Thread(test).start();
new Thread(test).start();
}
@Override
public synchronized void run() {
for (int i = 0; i < 5; i++) {
System.out.println(str1 + str2[i]);
}
}
}
請分析主程式運行輸出結果。
Runnable 實例 (test)。run() 方法加了 synchronized,鎖對象是 test 實例。run(),不會交錯輸出。this 1 this 2 this 3 this 4 this 5 this 1 this 2 this 3 this 4 this 5
或相反順序 (取決於執行緒調度)。
synchronized 實例方法鎖住 this (即共用的 Runnable 實例)。run() 不加同步,則會交錯輸出。new Ques0308(),則鎖不同,會交錯。