About Question enthuware.ocpjp.v21.2.3753 :

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
witek_m
Posts: 18
Joined: Sat Jun 09, 2018 12:09 pm
Contact:

About Question enthuware.ocpjp.v21.2.3753 :

Post 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.

admin
Site Admin
Posts: 10389
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post 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.

Post Reply

Who is online

Users browsing this forum: No registered users and 2 guests