다음 코드는 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();
}
}
if 문과 while 문의 차이점을 알고 있습니까? –
중복 된 질문에서 모든 대답에 놀라움을 금치 못했습니다. 단지 하나만 (나는 방금 전경을 털어 놓았습니다)에 가짜 웨이크 업을 언급합니다. 이 질문에 대한 정답은 "가짜 웨이크 업"입니다. –
예, 차이점을 알고 있습니다. 잠금을 사용할 수없는 경우 wait()가 현재 스레드를 중단한다고 가정합니다. 내 질문은 다음과 같이 표현할 수 있습니다. 스레드가 중단 된 경우 if 문이 아닌 while 루프를 사용해야하는 이유는 무엇입니까? – bookmonkie