有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么是线程。当前线程。中断()与返回相结合可以停止当前正在运行的线程

好吧,我正在试图理解为什么下面的线程组合。当前线程。当我想要终止当前线程时,interrupt()和return可以正常工作

Thread.currentThread.interrupt();
return;

我写了一个小程序:

public class Interr implements Runnable {
    @Override
    public void run() {
        for(int i= 0; i<10000;i++){
            System.out.println(i);
            if(i==500){
                Thread.currentThread().interrupt();
                return ;
            }
        }

    }   
    public static void main(String args []){
        Thread thread = new Thread(new Interr());
        thread.run();
    }
}

我知道我也可以用线。当前线程。stop()但是终止线程是一种不安全的方式。所以我尝试使用interupt()和return的组合

它是有效的,但我不理解它为什么有效

有什么解释吗

编辑:在上面的示例中,我是线程的所有者。假设,我不是线程的所有者。为什么这种组合会起作用


共 (3) 个答案

  1. # 1 楼答案

    无需从同一线程调用interrupt()

    中断方法将用于从其他线程中断一个线程

    根据java文档

    Interrupts this thread. Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.

    If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

    If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.

    If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.

    If none of the previous conditions hold then this thread's interrupt status will be set.

    Interrupting a thread that is not alive need not have any effect.

    因此,它将向I/O块中的线程发送中断信号

    @Override
    public void run() {
    
        while (true) {
    
        }
    }
    

    如果一个线程有这样的实现,即使调用了这个方法,它也不会中断

  2. # 2 楼答案

    实际上,在您发布的代码中,线程停止的原因是您调用了return

    根据documentation,调用Thread.interrupt()只不过是在调用它的线程上设置一个标志。线程的所有者检查标志,必须找到一种方法来停止它正在做的事情

  3. # 3 楼答案

    你不需要interrupt()return足够退出run(),这将导致线程停止,因为它没有更多的工作要做