Mega Code Archive

 
Categories / Java Tutorial / Thread
 

Guarantee that threads are woken in the same order in which they waited

import java.util.Vector; public class Wake {   private Vector<Object> stopped = new Vector<Object>();   public void stopOne() {     Object myLock = new Object();     synchronized (myLock) {       stopped.addElement(myLock);       try {         myLock.wait();       } catch (InterruptedException e) {       }     }   }   public void wakeOne() {     Object theLock = null;     synchronized (stopped) {       if (stopped.size() != 0) {         theLock = stopped.firstElement();         stopped.removeElementAt(0);       }     }     if (theLock != null) {       synchronized (theLock) {         theLock.notify();       }     }   }   public static void main(String args[]) {     Wake queue = new Wake();     Runnable r = new RunThis(queue);     Thread t;     for (int i = 0; i < 10; i++) {       t = new Thread(r);       t.start();     }     for (int i = 0; i < 11; i++) {       try {         Thread.sleep((long) (Math.random() * 1000));       } catch (InterruptedException e) {       }       System.out.println("About to wake one thread");       queue.wakeOne();     }   } } class RunThis implements Runnable {   Wake w;   public RunThis(Wake w) {     this.w = w;   }   public void run() {     System.out.println("Thread starting, name is " + Thread.currentThread().getName());     w.stopOne();     System.out.println("Thread woken up, name is " + Thread.currentThread().getName());   } }