Tutorials Hut

Java Multithreading: join Method, Difference Between start and run Methods

join method is used to ensure that the next thread(s) will only execute if the joined thread’s execution is complete. If we call join on any thread named t1 and there are other threads t2 and t3, first t1 will complete and then only t2 and t3 will start execution. This may look like against the multithreading feature, but in applications we may need some thread to complete before others start. In coming sections we will see the difference between start and run method as well.

Example of join method in Java Multithreading

See below example, t1 threads completes then only t2. And t3 starts running concurrently.

package threads;

public class JoinMethodExample {
public static void main(String[] args) throws InterruptedException {
DummyThread ob1 = new DummyThread();
    Thread t1 = new Thread(ob1);
    Thread t2 = new Thread(ob1);
     Thread t3 = new Thread(ob1);

    //Remember to start and join first, the thread you want to complete first.
    t1.start();
    t1.join();

    t2.start();
    t3.start();
}
}
class DummyThread implements Runnable {

@Override
public void run() {
    for(int i=0; i<2; i++) {
        try {
            System.out.println("Running in thread name" + Thread.currentThread().getName()+" i="+i);
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
}

Output

Running in thread nameThread-0 i=0
Running in thread nameThread-0 i=1
Running in thread nameThread-1 i=0
Running in thread nameThread-2 i=0
Running in thread nameThread-1 i=1
Running in thread nameThread-2 i=1

Difference between start and run Methods In Java

start() method ensures that whenever called, it will start a new thread and won’t run as part of the current thread, this helps in achieving actual multithreading. At the end the code in run() method will be executed as a separate thread.

run() method holds the logic of threading, but if we invoke it directly, it will start in the current thread and not as a new thread and that is why we should never call run directly, call start method and leave the rest of things to it.

Next Article














  • Leave a Reply

    Your email address will not be published. Required fields are marked *