Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the join() method of Thread class work?

Tags:

java

Consider the following code :

class ThreadJoinTest{
    public static void main(String[] arguments){
        TimeUnit unit; 
        final Thread taskThread = new Thread(task);
        taskThread.start();
        taskThread.join(unit.millis(timeout));   
     }
}

So when the main thread would execute the line taskThread.join() with a time out value, the main thread is giving the taskThread ample time to finish its task? Is this the main objective of the join method?

What will happen if:

  1. taskThread finishes its execution before the time out period?
  2. What happens if the timeout is reached but the taskThread has not finished executing? Does the taskThread get a chance to finish its task or not?
  3. How does the main thread know that join returned because the taskThread finished normally or because timeout was reached?
like image 818
Geek Avatar asked Jul 15 '12 15:07

Geek


2 Answers

  1. main will be allowed to start again as soon as taskThread is done.
  2. Then main will be allowed to start again, and taskThread will continue. Both threads will be allowed to finish.
  3. If either the taskThread finished normally or the timeout is reached main will continue to execute. There is no way for main to know if the timeout occurred or if taskThread finished executing without using some other means of communication.
like image 108
Keppil Avatar answered Oct 03 '22 22:10

Keppil


join() when called on the thread, will wait for that thread to die (ie for the run method of that thread to get done with..). Only then the line below the join() will execute. But giving a timeout within join(), will make the join() effect to be nullified after the specific timeout.

Though the timeout occurs, the taskThread will be allowed to finish the work.

like image 41
Kumar Vivek Mitra Avatar answered Oct 03 '22 23:10

Kumar Vivek Mitra