Page 1 of 1

About Question enthuware.ocpjp.v21.2.3753 :

Posted: Sun Jun 15, 2025 9:25 am
by witek_m
Java multithreading - how can this output with 4× RUNNABLE be valid?

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();
   }
}
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.

Re: About Question enthuware.ocpjp.v21.2.3753 :

Posted: Mon Jun 16, 2025 5:09 am
by admin
Yes, it is very likely that T1 will be interrupted while it is sleeping. However, it is also possible, even if highly unlikely, that the thread scheduler does not schedule the main thread to run after it wakes up from 300 ms sleep and decides to keep scheduling T1 (or some other thread such as GC thread) instead. Again, highly unlikely but possible. In that case, T1 RUNNABLE may be printed twice before the main thread interrupts it.

Thread.sleep(300); guarantees that the main thread will not call t1.interrupt() before 300 ms sleep is over but it does not guarantee that the main thread will execute t1.interrupt() immediately afterwards.