2013-07-02 2 views
1

wait() 및 notify()가 어떻게 작동하는지 알고 싶습니다. 나는 wait()와 notify()를 사용하여 작업을 수행 할 수 없었다. 대신 while() 루프를 사용하여 잠깐 기다리면 제대로 작동합니다. 그것은 어때? 단순히 wait() 및 notify() 만 사용하면 안되는 이유는 무엇입니까?대기 및 알림은 어떻게 작동합니까?

+2

지금까지 시도해 본 것과 달성하고자하는 것을 공유 할 수 있습니까? – Grimmy

+0

나는 run 메소드에서 대기하고 다른 메소드에서 통지했다. 내 프로그램은 이런 식으로 작동하고 대기는 전혀 실행되지 않습니다. – user2541450

+3

당신을 도울 수 있기 위해서 우리는 정말로 약간의 코드를 볼 필요가 있습니다! 동시성은 아주 미묘 할 수 있습니다. – selig

답변

3

wait() 및 notify()는 동기화 된 블록에서 사용되는 반면 스레드를 사용하여 중단 된 위치에서 다시 시작합니다.

기다림은 즉시 잠금을 해제하는 반면, 잠금은 끝 브래킷이 만났을 때만 잠금을 해제합니다.

또한이 샘플 예를 참조 할 수 있습니다 :

public class MyThread implements Runnable { 

    public synchronized void waitTest() { 
     System.out.println("Before Wait"); 
     wait(); 
     System.out.println("After Wait"); 
    } 

    public synchronized void notifyTest() { 
     System.out.println("Before Notify"); 
     notify(); 
     System.out.println("After Notify"); 
    } 
} 


public class Test { 

    public static void main(String[] args) { 
     Thread t = new Thread(new MyThread()); 
     t.start();  
    } 
} 
+1

명확성을 위해 샘플 출력을 추가 할 수 있습니까? – jnovacho

+1

/notifyAll()에 알릴 때 상태 변경을 수행해야하며 상태 변경을 기다릴 때() 상태를 확인하십시오. 이렇게하지 않으면 wait()가 notify()를 놓치거나 wait()가 가짜로 깨울 수 있습니다. –

4

당신이 wait의 문서를 읽고 - notify 기능을? 이 클래스의 각 인스턴스는 한 번만 사용되어야한다는 것을,

public class WaitNotifier { 
    private final Object monitoredObject = new Object(); 
    private boolean wasSignalled = false; 

    /** 
    * waits till another thread has called doNotify (or if this thread was interrupted), or don't if was already 
    * notified before 
    */ 
    public void doWait() { 
     synchronized (monitoredObject) { 
      while (!wasSignalled) { 
       try { 
        monitoredObject.wait(); 
       } catch (final InterruptedException e) { 
        break; 
       } 
      } 
      wasSignalled = false; 
     } 
    } 

    /** 
    * notifies the waiting thread . will notify it even if it's not waiting yet 
    */ 
    public void doNotify() { 
     synchronized (monitoredObject) { 
      wasSignalled = true; 
      monitoredObject.notify(); 
     } 
    } 

} 

이 메모를 수행하는 가장 좋은 방법은 대기 통지 메커니즘을 달성하기 위해

어쨌든, (this website 기준)이 같은 것을 사용 그래서 당신이 그것을 여러 번 사용해야 할 필요가 있다면 그것을 바꿀 수도 있습니다.

관련 문제