線程學習---對synchronized的測試
public class myThread extends Thread {
?public void run() {
??synchronized(System.out){
???for (int i = 0; i < 10; i++) {
????try{
?????sleep(100);
????}catch(InterruptedException e){e.printStackTrace();}
????
????System.out.println(getName() + ": i=" + i);
????if (i==9) System.out.println("=========");
???}
??}
?}
?public static void main(String[] a) {
??myThread thread1 = new myThread();
??myThread thread2 = new myThread();
??thread1.setName("A");thread1.start();
??thread2.setName("B");thread2.start();
?}
}
在這個測試中,由于執行所需時間片太短,如果不在其中加一句sleep(100)的話,線程A 和線程B的交叉就體現不出來,就更不用說驗證synchronized的作用了; 另,注意synchronized所同步的對象是System.out, 而不是this.
posted on 2007-05-22 09:34 心硯 閱讀(248) 評論(0) 編輯 收藏 所屬分類: Java