在下面的代碼中,我使用wait()-notify()實現了線程間通信,它給了我期望的輸出。 預計輸出:123456789實際輸出:123456789線程信號序列
我的問題是,是否有任何保證總是'主線程'將獲得第一次執行機會,因爲線程調度依賴於jvm。如果'子線程'獲得第一次機會,則notify()信號將會丟失,並且'主線程'將永遠等待。我如何確認'主線程'將始終執行。另請確認下面的代碼是否可以改進。
package com.test.Thread;
public class ThreadExample1 {
public static void main(String[] args) throws InterruptedException{
ThreadChild1 lockingObj = new ThreadChild1();
lockingObj .start();
synchronized(lockingObj){
for(int i=1;i<10;i++){
System.out.println("Main "+i);
}
lockingObj.wait();
System.out.println("Main got notified");
}
}
}
class ThreadChild1 extends Thread{
public void run(){
synchronized(this){
for(int i=1;i<10;i++){
System.out.println("Child "+i);
}
this.notify();
}
}
}
謝謝@Erwin。理解並糾正它。 – RoyalTiger