在下面的代碼中,如果我同步bar
方法,它在輸出方面沒有什麼不同 - 我做錯了什麼?我相信同步「欄」會使「ThreaOne」被打印10次,然後只打印「ThreadTwo」將開始,但事實並非如此。我得到的輸出中如下:簡單的線程同步問題
I am Test thread:Thread OneOneOneOne I am Test thread:Thread OneOneOneOne I am Test thread:Thread OneOneOneOne I am Test thread:Thread OneOneOneOne I am in main now I am Test thread:Thread OneOneOneOne I am Test thread:Thread Two I am Test thread:Thread Two I am Test thread:Thread OneOneOneOne I am Test thread:Thread Two I am Test thread:Thread OneOneOneOne I am Test thread:Thread Two I am Test thread:Thread OneOneOneOne I am Test thread:Thread Two I am Test thread:Thread OneOneOneOne I am Test thread:Thread Two I am Test thread:Thread OneOneOneOne I am Test thread:Thread Two I am Test thread:Thread Two I am Test thread:Thread Two I am Test thread:Thread Two I am in main now
等。這裏是我的代碼:
package com.rahul;
class ThreadTest implements Runnable{
@Override
public void run() {
bar();
}
public synchronized void bar() {
for(int i=0;i<10;i++){
System.out.println("I am Test thread:"+Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class Test{
public static void main(String[] args) {
Thread t1 = new Thread(new ThreadTest(),"Thread OneOneOneOne");
Thread t2 = new Thread(new ThreadTest(),"Thread Two");
t1.start();
try{
Thread.sleep(4000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t2.start();
while(true){
System.out.println("I am in main now");
try {
t2.join();
Thread.sleep(4000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
該死的,我錯過了。非常感謝Brian! – user1291291 2013-02-24 07:32:35