Can We Start a Thread Twice?
A common interview question is: can a thread be started twice? The answer is no. A Thread object can be started only once. Calling start() a second time, whether the thread is still running or already finished, throws IllegalThreadStateException. A finished thread is TERMINATED and can't be brought back. In this lesson, you will see the exception and learn the right way to run the same work again.
Example: Starting Twice
Let's see an example that tries to start the same thread two times.
public class StartTwice {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> System.out.println("Navika's task runs"));
t.start();
t.join();
System.out.println("State: " + t.getState());
try {
t.start();
} catch (IllegalThreadStateException e) {
System.out.println("Second start failed: "
+ e.getClass().getSimpleName());
}
}
}Navika's task runs
State: TERMINATED
Second start failed: IllegalThreadStateExceptionExplanation: The first start() runs the task, and the thread ends in the TERMINATED state. The second start() on the same object throws IllegalThreadStateException. The same exception is thrown if the thread is still running when start() is called again.
Why Java Forbids It
A thread's life cycle goes one way: NEW to RUNNABLE to TERMINATED. Restarting would mean reusing an operating-system thread's identity, state and stack in unclear ways. Instead, Java keeps the rule simple: one Thread object, one run.
The Right Way: A New Thread, or a Pool
public class RunAgain {
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> System.out.println("Task run by "
+ Thread.currentThread().getName());
for (int i = 1; i <= 2; i++) {
Thread t = new Thread(task, "run-" + i);
t.start();
t.join();
}
}
}Task run by run-1
Task run by run-2Explanation: The task (Runnable) can be reused as often as you like. Each run gets a new Thread object. In real applications, a thread pool reuses its own threads to run many tasks, so you never need to restart a thread.
Common Mistakes
Storing a Thread in a field and calling start() on every button click. The second click throws.
Assuming a finished thread returns to NEW. It stays TERMINATED forever.
Interview Corner
Can we start a thread twice in Java?
No. Thread.start() may be called only once per Thread object. A second call, whether the thread is running or has terminated, throws IllegalThreadStateException. To run the same work again, create a new Thread with the same Runnable, or submit the task to an ExecutorService, which reuses its worker threads.
Practice
- Easy: Show that calling
start()twice on a still-running thread (one that sleeps for a second) also throws. - Harder: Write a
Repeaterclass that runs aRunnablethree times, each in a new named thread, waiting for each to finish.
Key Takeaways
Was this tutorial helpful?