I was reading the implementation of interrupt in Java, but I could not figure out how the control is flowing?
The code snippet is:
public class Main implements Runnable
{
Thread t;
Main()
{
t = new Thread(this);
t.start();
t.interrupt();
if (!t.interrupted())
{
System.out.println("TRUE");
}
}
public void run()
{
try
{
System.out.println("Thread is in running state");
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.print(t.getName() + " interrupted");
}
}
public static void main(String args[])
{
new Main();
}
}
As per my understanding, by seeing the executing order in constructor it should be:
Thread is in running state
Thread-0 interrupted
TRUE
But this is WRONG.
The correct output is:
TRUE
Thread is in running state
Thread-0 interrupted
So please explain how this execution order work and why?
Edit 1: As pointed out that calling t.interrrupted()
is misleading so I changed the constructor to:
Main()
{
t = new Thread(this);
t.start();
t.interrupt();
if (!Thread.interrupted())
{
System.out.println("TRUE");
}
}
So now the output is:
TRUE
Thread is in running state
Thread-0 interrupted
Now the questions are,
- Since the thread is in the non-runnable state when t.interrupt() was called, then what does t.interrupt() do in that case?
- Why the last line of output is printed? From where does it get interrupt, because t.interrupt was executed when the thread was in the non-runnable state.
First, you are calling the wrong method.
As pointed out in another answer, interrupted()
is a static method that always checks the current thread's interrupt status. If you want to check t
's status, you should call t.isInterrupted()
.
Second, you have to remember that start()
does not guarantee that the thread begins execution immediately. In fact, that will rarely happen. The new thread will only actually begin execution when the scheduler tells it to do so.
So, what is happening is:
start()
, but the thread isn't actually starting yet interrupt()
call As for the answers to the EDIT:
if (!t.interrupted())
This line is misleading. interrupted()
is a static method that checks if the current thread has been interrupted, not the named thread. It would be a lot better if it were written:
if (!Thread.interrupted())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.