Junior — Middle
Is it possible to execute the start method twice in a row within a single thread?
sobes.tech AI
Answer from AI
In Java, the start() method of a Thread class object can only be called once. If you try to call start() a second time on the same thread object, an IllegalThreadStateException will be thrown.
This is because after starting, the thread transitions to the "started" state and cannot be started again. To run the code twice, you need to create a new Thread object and call start() on it.
Example:
Thread t = new Thread(() -> System.out.println("Thread started"));
t.start();
// t.start(); // will throw IllegalThreadStateException
Thread t2 = new Thread(() -> System.out.println("Second thread"));
t2.start();