| Author |
which is more efficient wait() and notify() or join() for this scenario?
|
Ajay Xavier
Ranch Hand
Joined: Jan 03, 2005
Posts: 109
|
|
hi, My aim is to stop the thread executing the "execute()" method until the new thread(fedthread) is completed. This can be acheived in two ways method 1: using wait and notify() as show below method 2: using join() as shown below public class Test { public void execute() { TestRun run = new TestRun(); Thread fedThread = new Thread(run); System.out.println("going to join the fedthread"); try { fedThread.start(); run.join(); } catch (Exception e) { e.printStackTrace(); } } System.out.println("after returning from the fedthread and continuing"); } } public class TestRun implements Runnable { public void run() { System.out.println("calling the fedthread"); try { Thread.sleep(5000); } catch (Exception e) { e.printStackTrace(); } } } which method is advantageous and more performance oriented? under which situations which method has to be follwed?
|
 |
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
|
|
|
Take a look at how Thread.join is implemented - if I'm not mistaken, it uses the wait/notify pattern itself.
|
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
|
 |
Stan James
(instanceof Sidekick)
Ranch Hand
Joined: Jan 29, 2003
Posts: 8791
|
|
|
Write for humans first. join() in T1 makes it clear to the reader you intend T1 to wait for T2 to complete the run() method. If you put your notify() at the end of run() in T2 then wait() in T1 has the same effect, but it's not obvious when reading T1 code.
|
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
|
 |
 |
|
|
subject: which is more efficient wait() and notify() or join() for this scenario?
|
|
|