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) { 
// 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() {
  synchronized (lock) {

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
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.