아래 코드에서 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();
}
}
}
감사합니다. @ 에윈. 그것을 이해하고 바로 잡았다. – RoyalTiger