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

标签 java multithreading interrupt interruption

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

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

最佳答案

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 产生影响,最低要求是 startinterrupt 方法之前调用 Thread

注意没有称为就绪状态的线程状态。您指的是RUNNABLE 状态,表示在 Thread 上调用了 start

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

相关文章:

java - 重命名 HDFS 上的文件在本地模式下有效,但在集群模式下无效

java - JTable table.getSelectedRows() 问题

Java邮件 : Searching for emails

c - 在 OpenMP 中启动多少个线程?

timer - 实时 Linux : disable local timer interrupts

c - 一个简单的 8051 C 中断事件计数器演示,不递增。

java - 将 vector 保存在列表中的方法

ios - 将任务分派(dispatch)到队列中以便在另一个线程中运行任务

java - 即使只有一个编写器线程, volatile 也会出现问题

linux-kernel - 我的中断处理程序应该禁用中断还是 ARM 处理器自动执行此操作?