wait 및 notify 메소드의 개념을 익히기 위해 간단한 Java 예제를 작성했습니다.if 조건 내에서 Java notify() 호출
notify()
을 호출하면 주 스레드가 합계를 인쇄합니다.
MyThread 클래스
public class MyThread extends Thread {
public int times = 0;
@Override
public void run() {
synchronized (this) {
try {
for (int i = 0; i < 10; i++) {
times += 1;
Thread.sleep(500);
if (i == 5) {
this.notify();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
메인 클래스
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
synchronized (t) {
t.start();
try {
t.wait();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(t.times);
}
}
}
예상 결과
5하지만 대신 10을 얻었다.
그래도 호출 될 때 notify()
, 메인 스레드가 웨이크 업하고 10 배의 값을 업데이트합니다 for 루프를 완료까지 5. 그런 다음 run()
가 계속 제공해야 System.out.println(t.times)
를 실행하는 것이 무엇인지 잘,
도움이 매우 감사합니다.
'notify '는 잠금을 해제하지 않습니다. – tkausl
이 문제에 대해 더 자세히 알려 주실 수 있습니까? – Mazen
[자바에서 wait() 및 notify()를 사용하는 간단한 시나리오] (http://stackoverflow.com/questions/2536692/a-simple-scenario-using-wait-and-notify-in-java)의 가능한 복제본 –