Java Multitasking  «Prev 

Podium's dequeue() method using Java Threads

And here is the dequeue() method we promised. Explanations for the emphasized code are provided below.

  public synchronized Object dequeue() { 
     Object ret; 
     while (anyoneLeft() && (super.elementCount == 0)) { 
        try { 
           wait(); 
        } catch (InterruptedException x) { 
        } 
      } 
      if (super.elementCount > 0) { 
        ret = super.firstElement(); 
        super.removeElement(ret); 
     } else { 
        ret = null; 
     } 
     return ret; 
   } 

wait() method

First, the podium makes sure there are speakers left. If there are, but there is currently nothing to be said, the podium waits.
The thread representing the podium (that is, the SynchronizedQueue instance) goes to sleep when it calls wait(). Every time it is awakened, which occurs whenever someone calls notify(), it checks to see whether the conditions that put it to sleep have changed. This thread will be notified:

  1. When a speaker checks out, and
  2. When a speaker says something

Accessing elements

The rest of the code in this method does the job of obtaining the first element in the queue and removing it from the queue. The method then returns what it found there, which will be a String instance representing what a citizen said (or null, if there are no more elements in the queue).