Executing a block of code after one of two parallel threads finish
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Andy_Sun
Posted On:   Friday, July 20, 2001 08:14 AM

I need to execute a block of code (or method) after which ever of two parallel threads finishes first without waiting for the other to finish. The logic is like: myVar = null; thread1; (may take 1 - 60 seconds) thread2; (takes 5 seconds) myMethod(myVar); (as soon as possible) How do I implement this? Please specify the critical structure, such as where to use synchronized or volatile or notify. I don't seem to fully grasp the relationships of these things. I tried to use notifyAll in the threads' run method, which results in runtime error. I also tried throwing exceptions at the end of the threads' run method which is not allowed. Without these mechanisms, myMethod won't even wait for the threads to    More>>

I need to execute a block of code (or method) after which ever of two parallel threads finishes first without waiting for the other to finish. The logic is like:

myVar = null;
thread1; (may take 1 - 60 seconds)
thread2; (takes 5 seconds)
myMethod(myVar); (as soon as possible)
How do I implement this?

Please specify the critical structure, such as where to use synchronized or volatile or notify. I don't seem to fully grasp the relationships of these things. I tried to use notifyAll in the threads' run method, which results in runtime error. I also tried throwing exceptions at the end of the threads' run method which is not allowed. Without these mechanisms, myMethod won't even wait for the threads to finish. Thanks.

   <<Less

Re: Executing a block of code after one of two parallel threads finish

Posted By:   Alex_Chaffee  
Posted On:   Monday, July 23, 2001 12:15 PM

Search the docs and FAQ for information on the method Thread.join(). It waits for a thread to quit.


Actually, rereading your message, you probably want to use object.notify. Like this:


Object lock = new Object();
Thread t1 = new ThreadOne(lock);
Thread t2 = new ThreadTwo(lock);
t1.start();
t2.start();
synchronized (lock) {
lock.wait();
}
// only reached after one thread has called lock.notify()
...


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

and the same pattern for ThreadTwo.


Search this FAQ for more info on wait and notify.

About | Sitemap | Contact