• Post Reply Bookmark Topic Watch Topic
  • New Topic

which is more efficient wait() and notify() or join() for this scenario?  RSS feed

 
Ajay Xavier
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at how Thread.join is implemented - if I'm not mistaken, it uses the wait/notify pattern itself.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!