2014-04-04 4 views
1

다음 코드는 http://www.programcreek.com/2009/02/notify-and-wait-example/대기()는 "만약"블록이나되는

에서 복사 블록 I는 대기()

을 래핑하는 while 루프를 사용하여 매우 몇 가지 예를 보았다 "하면서"내 질문 : 비슷한 문제를 해결하기위한 첫 번째 시도에서 if 문을 사용하여 wait()를 래핑했습니다. 예 :

if(messages.size() == MAXQUEUE) { 
     wait(); 
    } 

if 문 대신 while 루프를 사용하면 어떤 이점이 있습니까?

import java.util.Vector; 

class Producer extends Thread { 

    static final int MAXQUEUE = 5; 
    private Vector messages = new Vector(); 

    @Override 
    public void run() { 
     try { 
      while (true) { 
       putMessage(); 
       //sleep(5000); 
      } 
     } catch (InterruptedException e) { 
     } 
    } 

    private synchronized void putMessage() throws InterruptedException { 
     while (messages.size() == MAXQUEUE) { 
      wait(); 
     } 
     messages.addElement(new java.util.Date().toString()); 
     System.out.println("put message"); 
     notify(); 
     //Later, when the necessary event happens, the thread that is running it calls notify() from a block synchronized on the same object. 
    } 

    // Called by Consumer 
    public synchronized String getMessage() throws InterruptedException { 
     notify(); 
     while (messages.size() == 0) { 
      wait();//By executing wait() from a synchronized block, a thread gives up its hold on the lock and goes to sleep. 
     } 
     String message = (String) messages.firstElement(); 
     messages.removeElement(message); 
     return message; 
    } 
} 

class Consumer extends Thread { 

    Producer producer; 

    Consumer(Producer p) { 
     producer = p; 
    } 

    @Override 
    public void run() { 
     try { 
      while (true) { 
       String message = producer.getMessage(); 
       System.out.println("Got message: " + message); 
       //sleep(200); 
      } 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 

    public static void main(String args[]) { 
     Producer producer = new Producer(); 
     producer.start(); 
     new Consumer(producer).start(); 
    } 
} 
+2

if 문과 while 문의 차이점을 알고 있습니까? –

+3

중복 된 질문에서 모든 대답에 놀라움을 금치 못했습니다. 단지 하나만 (나는 방금 전경을 털어 놓았습니다)에 가짜 웨이크 업을 언급합니다. 이 질문에 대한 정답은 "가짜 웨이크 업"입니다. –

+0

예, 차이점을 알고 있습니다. 잠금을 사용할 수없는 경우 wait()가 현재 스레드를 중단한다고 가정합니다. 내 질문은 다음과 같이 표현할 수 있습니다. 스레드가 중단 된 경우 if 문이 아닌 while 루프를 사용해야하는 이유는 무엇입니까? – bookmonkie

답변

9

은 대기가()도 (이이 documentation에 "가짜 웨이크 업"이라고합니다) 적극적으로 통보하지 않은 기다렸다되고있는 객체 불구하고 반환 할 수 있습니다. wait() 호출을 while 루프로 감싸는 것이 더 의미가 있습니다. while 루프는 기다려야 할 실제 조건이 만족되는지 여부를 확인하고 wait()이 아니라면 wait()를 다시 호출합니다.)는 실제로 기다리고있는 이벤트를 반환합니다.

3

대기 알림을 받으면 루프가 실행되고 실행이 시작됩니다. 대기가 통보되었지만 대기열이 꽉 차더라도 계속 진행해서는 안되는 것이 더 좋습니다. 따라서 대기열이 비어있을 때까지 대기합니다. 질문에 답변하시기 바랍니다.

관련 문제