나는 다음과 같은 프로그램이 있습니다이해 자바 대기 및 통지 방법
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SimpleWaitNotify implements Runnable {
final static Object obj = new Object();
static boolean value = true;
public synchronized void flag() {
System.out.println("Before Wait");
try {
obj.wait();
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
System.out.println("After Being Notified");
}
public synchronized void unflag() {
System.out.println("Before Notify All");
obj.notifyAll();
System.out.println("After Notify All Method Call");
}
public void run() {
if (value) {
flag();
} else {
unflag();
}
}
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(4);
SimpleWaitNotify sWait = new SimpleWaitNotify();
pool.execute(sWait);
SimpleWaitNotify.value = false;
SimpleWaitNotify sNotify = new SimpleWaitNotify();
pool.execute(sNotify);
pool.shutdown();
}
}
내가 OBJ에서 대기, 나는 두 개의 스레드 각각에 대해 다음과 같은 예외 Exception in thread "pool-1-thread-1" java.lang.IllegalMonitorStateException: current thread not owner
를 얻을 수 있습니다.
그러나 SimpleWaitNotify의 모니터를 사용하면 프로그램 실행이 일시 중단됩니다. 즉, 현재 실행 스레드 및 실행 프로그램을 일시 중단한다고 생각합니다. 진행 상황에 대한 이해를 돕기 위해 도움을받을 수 있습니다.
이것은 이론과 javadoc이 단순한 것처럼 보이는 영역이며 많은 예제가 없기 때문에 개념적으로 나에게 큰 차이가 남았습니다.
좋아요. 복합 객체'obj'를 완전히 없애 버리면 같은 결과를 얻을 수 있습니까? – Maddy
@Maddy : "this"를 기다리고 기다릴 수 있어야합니다. 일반적으로 "this"는 다른 코드가 효과적으로 액세스 할 수있는 참조이므로 일반적으로 나쁜 생각입니다. 코드 만 알고있는 객체에 대한 개인 참조를 유지하는 것이 좋습니다. –
좋은 지적. 동의했다. – Maddy