我研究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/