How do I exacute a block of code after the first of two threads finishes, no matter which one finishes first?

Alex Chaffee

You probably want to use object.notify. Like this:

Object lock = new Object();
Thread t1 = new MyThread(lock);
Thread t2 = new MyThread(lock);

 synchronized (lock) { 
  t1.start();
  t2.start(); 
  lock.wait();
 }
// only reached after one thread has called lock.notify()
  ...


class MyThread extends Thread {
 Object lock;
 public MyThread(Object lock) {
  this.lock = lock;
 }
 public void run() {
  doThing();
  synchronized (lock) {
   lock.notify();
  }
 }
}

Search this FAQ for more info on wait and notify. (Use the "Search" box in the upper-right corner.)

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact