我有2個線程t1和t2,它將打印1到10. t1線程將打印奇數,而t2線程將打印偶數。我很困惑,我怎麼會知道這個線程是t1或t2,並且打印1到10應該按順序完成。我最終這樣做了。請建議我是哪裏出錯了。等待並通知2個並行運行線程
class Print implements Runnable{
Object odd = new Object();
public void run() {
for (int i = 1; i <= 10; i ++){
if(Thread.currentThread().getName().equals("t1")){
synchronized(odd){
if ((i %2 !=0))
System.out.println(i + " Thread - " + Thread.currentThread().getName());
try {
odd.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
if(Thread.currentThread().getName().equals("t2")){
synchronized(odd){
if ((i %2 ==0)){
System.out.println(i + " Thread - " + Thread.currentThread().getName());
odd.notifyAll();
}
}
}
}
}
}
public class EvenOdd {
public static void main(String[] args) {
Print obj1 = new Print();
Print obj2 = new Print();
Thread t1 = new Thread(obj1, "t1");
Thread t2 = new Thread(obj2, "t2");
t1.start();
t2.start();
}
}
輸出:
1螺紋 - T1 2螺紋 - T2 4螺紋 - T2 6螺紋 - T2 8螺紋 - T2 10螺紋 - T2
如果你期望按順序行事,那你爲什麼需要線程? –
這不是關於順序,但我如何控制兩個並行運行線程的執行以打印1到10. t1打印1並等待t2打印2,然後t1打印3等等。希望你明白我的觀點。謝謝 – Rajat