Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Multithreading concept and join() method

I'm confused in join() method used in Threads in Java. In the following code:

// Using join() to wait for threads to finish. class NewThread implements Runnable {      String name; // name of thread     Thread t;      NewThread(String threadname) {         name = threadname;         t = new Thread(this, name);         System.out.println("New thread: " + t);         t.start(); // Start the thread     } // This is the entry point for thread.      public void run() {         try {             for (int i = 5; i > 0; i--) {                 System.out.println(name + ": " + i);                 Thread.sleep(1000);             }         } catch (InterruptedException e) {             System.out.println(name + " interrupted.");         }         System.out.println(name + " exiting.");     } }  class DemoJoin {      public static void main(String args[]) {         NewThread ob1 = new NewThread("One");         NewThread ob2 = new NewThread("Two");         NewThread ob3 = new NewThread("Three");         System.out.println("Thread One is alive: "                 + ob1.t.isAlive());         System.out.println("Thread Two is alive: "                 + ob2.t.isAlive());         System.out.println("Thread Three is alive: "                 + ob3.t.isAlive()); // wait for threads to finish         try {             System.out.println("Waiting for threads to finish.");             ob1.t.join();             ob2.t.join();             ob3.t.join();         } catch (InterruptedException e) {             System.out.println("Main thread Interrupted");         }         System.out.println("Thread One is alive: "                 + ob1.t.isAlive());         System.out.println("Thread Two is alive: "                 + ob2.t.isAlive());         System.out.println("Thread Three is alive: "                 + ob3.t.isAlive());         System.out.println("Main thread exiting.");     } } 

Sample output from this program is shown here:

New thread: Thread[One,5,main] New thread: Thread[Two,5,main] New thread: Thread[Three,5,main] Thread One is alive: true Thread Two is alive: true Thread Three is alive: true Waiting for threads to finish. One: 5 Two: 5 Three: 5 One: 4 Two: 4 Three: 4 One: 3 Two: 3 Three: 3 One: 2 Two: 2 Three: 2 One: 1 Two: 1 Three: 1 Two exiting. Three exiting. One exiting. Thread One is alive: false Thread Two is alive: false Thread Three is alive: false Main thread Exiting 

In the above code :

  1. I'm not able to understand the flow of execution of the program, And when ob1 is created then the constructor is called where t.start() is written but still run() method is not executed rather main() method continues execution. So why is this happening?

  2. join() method is used to wait until the thread on which it is called does not terminates, but here in output we see alternate outputs of the thread why??

And if the use of join is this then what is the use of synchronized??

I know I'm missing a basic concept here, but I'm not able to figure it out so please help.

like image 924
user2696258 Avatar asked Aug 28 '13 05:08

user2696258


People also ask

What is the role of join () in multithreading?

Join is a synchronization method that blocks the calling thread (that is, the thread that calls the method) until the thread whose Join method is called has completed. Use this method to ensure that a thread has been terminated. The caller will block indefinitely if the thread does not terminate.

What is thread join () in threading?

join() is holding up the main thread. All three threads complete before the t1. join() finishes and the main thread moves on to execute the print then t2. join() then print then t3. join() then print.

What is thread join in Java example?

Java Thread join() method The join() method of thread class waits for a thread to die. It is used when you want one thread to wait for completion of another. This process is like a relay race where the second runner waits until the first runner comes and hand over the flag to him.

Is join a method of thread class?

A join() is a final method of Thread class and it can be used to join the start of a thread's execution to the end of another thread's execution so that a thread will not start running until another thread has ended.


2 Answers

You must understand , threads scheduling is controlled by thread scheduler.So, you cannot guarantee the order of execution of threads under normal circumstances.

However, you can use join() to wait for a thread to complete its work.

For example, in your case

ob1.t.join(); 

This statement will not return until thread 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 wait for thread t to finish.

NOTE that t.join did not do anything to thread t or to thread t1. It only affected the thread that called it (i.e., the main() thread).

Edited:

t.join(); needs to be inside the try block because it throws the InterruptedException exception, otherwise you will get an error at compile time. So, it should be:

try{     t.join(); }catch(InterruptedException e){     // ... } 
like image 165
Malwaregeek Avatar answered Sep 22 '22 14:09

Malwaregeek


First of all, when you create ob1 then constructor is called and it starts execution. At that time t.start() also runs in separate thread. Remember when a new thread is created, it runs parallely to main thread. And thats why main start execution again with next statement.

And Join() statement is used to prevent the child thread from becoming orphan. Means if you did'nt call join() in your main class, then main thread will exit after its execution and child thread will be still there executing the statements. Join() will wait until all child thread complete its execution and then only main method will exit.

Go through this article, helps a lot.

like image 24
Vimal Bera Avatar answered Sep 20 '22 14:09

Vimal Bera