Java – wait () is an “if” block or a “while” block
•
Java
See English answers > why should wait() always be called inside a loop
I've seen many examples of using a while loop to wrap wait ()
My problem: when I first tried to solve a similar problem, I used an IF statement to wrap wait () For example,
if(messages.size() == MAXQUEUE) { wait(); }
What are the benefits of using a while loop instead of an IF statement?
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(); } }
Solution
Even if the waiting object is not actively notified by you, wait () may return (this is called "false wake-up" in documentation) That's why it's more reasonable to wrap the wait () call into a while loop to check whether the actual conditions you want to wait are met and call wait () again instead of simply assuming that the waiting time is more reasonable.) Returns the event you actually waited for
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码