No, we cannot start Thread again, doing so will throw runtimeException java.lang.IllegalThreadStateException. The reason is once run() method is executed by Thread, it goes into dead state.
Let’s take an example-
Thinking of starting thread again and calling start() method on it (which internally is going to call run() method) for us is some what like asking dead man to wake up and run. As, after completing his life person goes to dead state.
Program to show that IllegalThreadStateException is thrown when we try to start thread again>
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyClass implements Runnable{
@Override
public void run() {
System.out.println("in run() method, method completed.");
}
public static void main(String[] args) {
MyClass obj=new MyClass();
Thread thread1=new Thread(obj,"Thread-1");
thread1.start();
thread1.start(); //will throw java.lang.IllegalThreadStateException at runtime
}
}
/*OUTPUT
in run() method, method completed.
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
*/
|
Must read links to get in depth knowledge of run() and start() methods-
What will happen if we don’t override run method of thread?
What will happen if we override start method of thread?
RELATED LINKS>
run() and Start() methods >
What will happen if we don’t override run method of thread?
What will happen if we override start method of thread?
Difference between starting thread with run() and start() methods in java
Can we start Thread again?
Volatile keyword vs synchronized>
Volatile keyword in java- difference between synchronized and volatile, 10 key points about volatile keyword, why volatile variables are not cached in memory
Differences between synchronized and volatile keyword in detail
Race Condition >