About Question enthuware.ocpjp.v17.2.3751 :
Moderator: admin
-
- Posts: 12
- Joined: Sat Dec 02, 2023 12:54 pm
- Contact:
About Question enthuware.ocpjp.v17.2.3751 :
If Main thread sleeps and exits first, then child thread gets a chance to run. Will it receive the interrupted status?
-
- Site Admin
- Posts: 10068
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v17.2.3751 :
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.
-
- Posts: 12
- Joined: Sat Dec 02, 2023 12:54 pm
- Contact:
Re: About Question enthuware.ocpjp.v17.2.3751 :
Here is the code
I don't understand option 2.
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
}
}
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?It will run and end cleanly if //1 is replaced with while(!isInterrupted()) { }; and a.interrupt(); is inserted at //2.
-
- Site Admin
- Posts: 10068
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v17.2.3751 :
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.
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.
-
- Posts: 12
- Joined: Sat Dec 02, 2023 12:54 pm
- Contact:
Re: About Question enthuware.ocpjp.v17.2.3751 :
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.
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.
Who is online
Users browsing this forum: No registered users and 134 guests