java - 为什么 isInterrupted() 给出 Thread.currentThread().isInterrupted() 以外的结果(JAVA)

标签 java multithreading

我研究java线程,一时看不懂: 在下面的代码中

public class ThreadsTest {
    public static void main(String[] args) throws Exception{

        ExtendsThread extendsThread = new ExtendsThread();
        Thread et = new Thread(extendsThread);
        et.start();    
        Thread.sleep(1500);
        ir.interrupt();               
    }      
}

public class ExtendsThread extends Thread {
    private Thread currentThread = Thread.currentThread();
    public void run() {
        while (!currentThread .isInterrupted()) {}
        System.out.println("ExtendsThread " + currentThread().isInterrupted());

    }
}

线程不会停止。 但是如果在 ExtendsThread 类中我检查 while (!Thread.currentThread().isInterrupted()) 线程停止。 为什么 private Thread currentThread = Thread.currentThread(); 不引用当前线程?

最佳答案

Why private Thread currentThread = Thread.currentThread(); doesn't refer to current thread?

因为在这个变量初始化的时候,你在主线程上。 (该变量在您执行 ExtendsThread extendsThread = new ExtendsThread(); 时初始化,这是从 main 完成的。)


但是,代码还有其他问题。

  • 您正在检查 currentThread 而不是 this 线程的中断。因此,首先将 ExtendsThread 代码更改为:

    class ExtendsThread extends Thread {
        public void run() {
            while (!isInterrupted()) {
            }
            System.out.println("ExtendsThread " + isInterrupted());
        }
    }
    
  • 然后你把继承搞砸了。当您这样做时:

    ExtendsThread extendsThread = new ExtendsThread();
    Thread et = new Thread(extendsThread);
    

    这意味着您将一个线程包裹在另一个线程中。 (因此,当您中断时,您正在中断外线程,但您正在检查内线程上的中断。)您可能只想摆脱包装线程,然后做

    ExtendsThread et = new ExtendsThread();
    

这是您代码的完整工作版本:

public class ThreadsTest {

    public static void main(String[] args) throws Exception{
        ExtendsThread et = new ExtendsThread();
        et.start();
        Thread.sleep(1500);
        et.interrupt();
    }
}

class ExtendsThread extends Thread {
    public void run() {
        while (!isInterrupted()) {
        }
        System.out.println("ExtendsThread " + isInterrupted());
    }
}

关于java - 为什么 isInterrupted() 给出 Thread.currentThread().isInterrupted() 以外的结果(JAVA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28628870/

相关文章:

java - 为什么不能重新启动 Java Thread 对象?

java - 我怎样才能让这个方法返回一个数组?

java - 如何将参数传递给java中已经运行的线程?

java - 设置 DownloadManager 的目标路径

java - 在按钮单击内显示加载 GIF,并在执行操作后再次隐藏它

java - 在 byte[] 之外的内存中创建 zip 文件。 Zip 文件总是损坏

c# - 线程锁内的多线程

PHP + pthreads : Build one big object - parallel-processing

java - Java 中 hashmap.get 和 treemap.get 谁更快

java - Netty的并发编码