Page 1 of 1

About Question enthuware.ocpjp.v17.2.3751 :

Posted: Wed Dec 20, 2023 12:47 pm
by yulinxp
If Main thread sleeps and exits first, then child thread gets a chance to run. Will it receive the interrupted status?

Re: About Question enthuware.ocpjp.v17.2.3751 :

Posted: Wed Dec 20, 2023 10:44 pm
by admin
Please post complete code that you tried and the output that you expected.

Re: About Question enthuware.ocpjp.v17.2.3751 :

Posted: Thu Dec 21, 2023 12:42 am
by yulinxp
Here is the code

Code: Select all

class A extends Thread
{
   boolean flag = true;
   public void run()
   {
      System.out.println("Starting loop");

      while( flag ){ };   //1

      System.out.println("Ending loop");
   }
}
public class TestClass
{
   public static void main(String args[]) throws Exception
   {
      A a = new A();
      a.start();
      Thread.sleep(1000);

      //2

   }
}
I don't understand option 2.
It will run and end cleanly if //1 is replaced with while(!isInterrupted()) { }; and a.interrupt(); is inserted at //2.
My question is: Main thread can sleep and exit first before child thread gets a chance to run. If that is the case, how can child thread receive the interrupted status?

Re: About Question enthuware.ocpjp.v17.2.3751 :

Posted: Thu Dec 21, 2023 3:42 am
by admin
Since a.start() has been called, that thread is already alive (doesn't matter if it is running or not). Now, if, before the main thread exits, it calls a.interrupt() then the other thread's interrupted status will be set to true. The other thread can check its interrupted status by calling isInterrupted().
I am not sure what is the confusion in that. You can check the JavaDoc API for details.

Re: About Question enthuware.ocpjp.v17.2.3751 :

Posted: Thu Dec 21, 2023 10:48 am
by yulinxp
Thanks for the explanation. I was confused on alive vs running. I got below from JavaDoc.

isAlive(): A thread is alive if it has been started and has not yet terminated.
start(): Schedules this thread to begin execution
Interrupt(): Interrupting a thread that is not alive need not have any effect.