gpt4 book ai didi

java - 线程是否需要处于 RUNNABLE 状态才能被中断?

转载 作者:行者123 更新时间:2023-11-30 07:51:22 25 4
gpt4 key购买 nike

java中的线程在被interrupt方法打断之前是否必须处于就绪状态?我试图通过在下面输入上面给定的代码来检查这一点。

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

根据代码可以看出,中断方法首先被主线程调用。最后我想问一下,有没有可能在线程启动之前首先执行中断调用的情况?

最佳答案

Is it necessary for a thread in java to be in ready state before it gets interrupted by interrupt method?

interrupt 方法并不真正中断线程。它只设置调用它的线程的中断状态。也就是说,如果您反转对 interrupt 方法和 start 方法的调用,您会注意到 Thread 没有被中断。

MyThread t = new MyThread();
t.interrupt();
t.start();

这应该确认 Thread.interrupt 方法对 Thread 有影响,最低要求是 start 是在 interrupt 方法之前调用了 Thread

注意 没有称为就绪状态的线程状态。你指的是 RUNNABLE 状态,表示在 Thread

上调用了 start

关于java - 线程是否需要处于 RUNNABLE 状态才能被中断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47238048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com