What happens if you Restart a Thread that has Already Started

Get the following exception:

Exception in thread “main” java.lang.IllegalThreadStateException

at java.lang.Thread.start(Thread.java:595)

at deadlock.DeadlockTest.main(DeadlockTest.java:38)

If you attempt to restart a thread in Java that has already been started and is still running, it will result in an IllegalThreadStateException. This exception is thrown to indicate that a thread operation is not permitted in its current state. Once a thread has been started and is actively running, trying to restart it by calling the start() method again will lead to this exception.

Here’s an example of how it can occur:

java
public class RestartThreadExample {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start(); // Start the thread
// Attempt to restart the thread while it’s still running
myThread.start(); // This will throw IllegalThreadStateException
}
}

class MyThread extends Thread {
@Override
public void run() {
// Thread’s execution logic
}
}

In this example, calling myThread.start() a second time after the thread has already started will result in an IllegalThreadStateException. To restart a thread, you should create a new instance of the thread class and start the new instance.