About Question enthuware.ocpjp.v17.2.3751 :

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

Moderator: admin

Post Reply
yulinxp
Posts: 12
Joined: Sat Dec 02, 2023 12:54 pm
Contact:

About Question enthuware.ocpjp.v17.2.3751 :

Post by yulinxp »

If Main thread sleeps and exits first, then child thread gets a chance to run. Will it receive the interrupted status?

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

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

Post by admin »

Please post complete code that you tried and the output that you expected.
If you like our products and services, please help us by posting your review here.

yulinxp
Posts: 12
Joined: Sat Dec 02, 2023 12:54 pm
Contact:

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

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

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

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

Post 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.
If you like our products and services, please help us by posting your review here.

yulinxp
Posts: 12
Joined: Sat Dec 02, 2023 12:54 pm
Contact:

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

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

Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 230 guests