java中的线程在被中断方法中断之前是否必须处于就绪状态?
我尝试通过在下面输入上面给出的代码来检查这一点。
class MyThread extends Thread
{
public void run() {
try
{
for(int i =0;i<10;i++) {
System.out.println("I am lazy thread");
Thread.sleep(2000);
}
}
catch(InterruptedException e) {
System.out.println("I got interrupted");
}
}
}
public class SleepAndInterruptDemonstrationByDurga {
public static void main(String[] args) {
MyThread t= new MyThread();
t.start();
t.interrupt();
System.out.println("End of main thread");
}
}
即使尝试了很多次,我得到的输出始终是下面的
End of main thread
I am lazy thread
I got interrupted
为什么不能输出
I am lazy thread
I got interrupted
End of main thread
根据代码可以看出,interrupt方法首先被主线程调用。最后我想问一下,在线程启动之前首先执行中断调用时,是否有任何可能的情况?
java中的线程在执行之前是否必须处于就绪状态
被中断方法中断?
The interrupt
方法并没有真正中断线程。它仅设置调用它的线程的中断状态。也就是说,如果您将呼叫反转到interrupt
方法和start
方法,你会注意到Thread
不会被打扰。
MyThread t = new MyThread();
t.interrupt();
t.start();
这应该证实对于Thread.interrupt
方法来影响Thread
,最低要求是start
被称为Thread
之前interrupt
method.
Note没有称为就绪状态的线程状态。你指的是RUNNABLE https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.State.html#RUNNABLE状态表明start
被称为Thread
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)