Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Not a queue example, but extremely simple :)</p> <pre><code>class MyHouse { private boolean pizzaArrived = false; public void eatPizza(){ synchronized(this){ while(!pizzaArrived){ wait(); } } System.out.println("yumyum.."); } public void pizzaGuy(){ synchronized(this){ this.pizzaArrived = true; notifyAll(); } } } </code></pre> <p>Some important points:<br> 1) NEVER do</p> <pre><code> if(!pizzaArrived){ wait(); } </code></pre> <p>Always use while(condition), because </p> <ul> <li>a) threads can sporadically awake from waiting state without being notified by anyone. (even when the pizza guy didn't ring the chime, somebody would decide try eating the pizza.). </li> <li>b) You should check for the condition again after acquiring the synchronized lock. Let's say pizza don't last forever. You awake, line-up for the pizza, but it's not enough for everybody. If you don't check, you might eat paper! :) (probably better example would be <code>while(!pizzaExists){ wait(); }</code>.</li> </ul> <p>2) You must hold the lock (synchronized) before invoking wait/nofity. Threads also have to acquire lock before waking. </p> <p>3) Try to avoid acquiring any lock within your synchronized block and strive to not invoke alien methods (methods you don't know for sure what they are doing). If you have to, make sure to take measures to avoid deadlocks. </p> <p>4) Be careful with notify(). Stick with notifyAll() until you know what you are doing.</p> <p>5)Last, but not least, read <a href="http://www.javaconcurrencyinpractice.com/" rel="noreferrer">Java Concurrency in Practice</a>!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload