How do I exacute a block of code after the first of two threads finishes, no matter which one finishes first?
Created May 7, 2012
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.)