About Question enthuware.ocpjp.v21.2.3753 :
Posted: Sun Jun 15, 2025 9:25 am
Java multithreading - how can this output with 4× RUNNABLE be valid?
I have the following code:
One of the correct outputs accepted by the test is:
T1 RUNNABLE
T2 RUNNABLE
T2 RUNNABLE
T1 RUNNABLE
How is it possible that T1 manages to print RUNNABLE before the interruption, given the sleep(1000) and only 300 ms before interrupt() is called?
In my opinion, a more likely scenario is that only one thread gets CPU time at first (e.g. T2), so it completes both RUNNABLE prints before T1 even starts. As a result, the interrupt() has no effect, because T1 hasn't reached sleep() yet, and then T1 runs and prints RUNNABLE twice as well.
I have the following code:
Code: Select all
class T extends Thread
{
public T(String name){ super(name); }
public void run()
{
try{
for(int i=0; i<2; i++){
Thread.sleep(1000);
System.out.println(getName()+" "+getState());
}
}catch(InterruptedException ie){
System.out.println(getName()+" "+getState()+" ");
}
}
}
public class TestClass
{
public static void main(String args[]) throws Exception
{
T t1 = new T("T1");
t1.start();
T t2 = new T("T2");
t2.start();
Thread.sleep(300);
t1.interrupt();
}
}
T1 RUNNABLE
T2 RUNNABLE
T2 RUNNABLE
T1 RUNNABLE
How is it possible that T1 manages to print RUNNABLE before the interruption, given the sleep(1000) and only 300 ms before interrupt() is called?
In my opinion, a more likely scenario is that only one thread gets CPU time at first (e.g. T2), so it completes both RUNNABLE prints before T1 even starts. As a result, the interrupt() has no effect, because T1 hasn't reached sleep() yet, and then T1 runs and prints RUNNABLE twice as well.