Saturday, August 27, 2016

Join

Concepts 1
You must understand , threads scheduling is controlled by thread scheduler.So, you cannot guarantee the order of execution of threads under normal circumstances.
However if you use join() ,it makes sure that as soon as a thread calls join,the current thread(yes,currently running thread) will not execute unless the thread you have called join is finished.
For example, in your case
ob1.t.join();
This will make sure that the current running thread will run only after t has finished running.
Try this,
class Demo {
   Thread t = new Thread(
                 new Runnable() {
                     public void run () {
                         //do something
                     }
                  }
    );
    Thread t1 = new Thread(
                 new Runnable() {
                     public void run () {
                         //do something
                     }
                  }
    );
    t.start(); // Line 15
    t.join();  // Line 16
    t1.start();
}
In the above example, your main thread is executing. When it encounters line 15, thread t is available at thread scheduler. As soon as main thread comes to line 16, it will not execute unless thread t has finished( remember join() as the currently running thread will join to the end of the thread on which join is called).Hence main thread will come to line 17 only when thread t has finished.
So it may appear that t.join will affect thread t1, but it is actually affecting main thread.


Syntax
  1. public void join() throws InterruptedException
  2. public void join(long miliseconds) throws InterruptedException

No comments:

Post a Comment

Required details

--------------------------------------------------------------------------------------------------------------------------- C:\Program File...