DEV Community

Cover image for About thread join and run method in Java
Lydia Yuan
Lydia Yuan

Posted on

About thread join and run method in Java

When you invoke run(), if the thread was initially created using a distinct Runnable run object, then the run method of that Runnable object is executed. Otherwise, if the thread was constructed without a separate Runnable object, the method does nothing and returns.

Surprisingly, even if the thread has already completed or terminated, as indicated by the first thread.join(), calling thread.run() will still execute and print output. Cuz this line of code calls the run() method directly, not starting a new thread.

Additionally, calling multiple join() statements will not result in any exceptions being thrown.

class JoinExample {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> System.out.println("Thread is running with runnable..."));

        thread.start();
        thread.join(); // Waits for the thread to complete
        thread.run();  // Calls the run() method directly, not starting a new thread
        thread.join(); // Waits again, no exception here

        // Second start will cause an IllegalThreadStateException
        // thread.start();
    }
}

//Output:
//Thread is running with runnable...
//Thread is running with runnable...
Enter fullscreen mode Exit fullscreen mode
class JoinExample {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread();

        thread.start();
        thread.join(); // Waits for the thread to complete
        thread.run();  // Calls the run() method directly, not starting a new thread
        thread.join(); // Waits again, no exception here

        // Second start will cause an IllegalThreadStateException
        // thread.start();
    }
}

//Output:
// nothing
Enter fullscreen mode Exit fullscreen mode

Top comments (0)