You can join two threads in Java by using join() method from java.lang.Thread class. Why do you join threads? because, you want one thread to wait for another before starts processing. It's like a relay race where second runner waits until first runner comes and hand over flag to him. Remember, unlike sleep(), join() is not a static method so you need an object of java.lang.Thread class to call this method. Now, who calls and who waits and which thread dies? for example, if you have two threads in your program main thread and T1 which you have created. Now if your main thread execute this line T1.join() (main thread execute whatever you have written in main method) then main thread will wait for T1 thread to finish its execution. Immediate effect of this call would be that main thread will stop processing immediately and will not start until T1 thread has finished. So, what will happen if T1 is not yet started and there is no one to start T1 thread? Well, then you have a deadlock but if its already finished then main thread will start again, provided it get the CPU back. In this tutorial, you will learn how to make three threads execute in a order by using join() method. You an also check out Java Threads By Scott Oaks and Henry Wong to get a good starting overview of several fundamentals of threads and multi-threading.
Read more »
No comments:
Post a Comment