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...
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
Top comments (0)