为什么isInterrupted()给出了除Thread.currentThread()之外的其他结果.isInterrupted()(JAVA)

时间:2015-02-20 12:20:03

标签: 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();不引用当前线程?

3 个答案:

答案 0 :(得分:3)

  

为什么私有Thread currentThread = Thread.currentThread();不引用当前线程?

因为在这个变量初始化时,你在主线程上。 (当您执行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());
    }
}

答案 1 :(得分:1)

创建ExtendsThread时,您将调用构造函数的线程分配给currentThread。所以你的currentThread实际上并不是你想象的那样。

答案 2 :(得分:0)

你应该在Thread currentThread = Thread.currentThread();run()。否则currentThread指的是主线程(构造对象的线程),但run由不同的线程执行