java中有两个代码块。
区块一:
@Test
public void test1() {
System.out.println("interrupt:" + Thread.currentThread().isInterrupted());
Thread.currentThread().interrupt();
System.out.println("interrupt:" + Thread.currentThread().isInterrupted());
}
输出:
interrupt:false
interrupt:true
区块二:
@Test
public void test2() throws InterruptedException {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("running...");
}
});
thread.interrupt();
TimeUnit.SECONDS.sleep(2);
System.out.println("interrupt:" + thread.isInterrupted());
thread.start();
TimeUnit.SECONDS.sleep(2);
System.out.println("interrupt:" + thread.isInterrupted());
}
输出:
interrupt:false
running...
interrupt:false
所以,我的问题:
interrupt:true
后阻止一个打印 interrupt()
而阻止两个? 谢谢!
PS:区块三:
@Test
public void test3() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("running...");
}
});
thread.interrupt();
System.out.println("interrupt:" + thread.isInterrupted());
// thread.start();
//
// thread.interrupt();
//
//
// System.out.println("interrupt:" + thread.isInterrupted());
}
还输出:
interrupt:false
最佳答案
尝试在 run() 方法中添加 Thread.sleep(5000);并在中断之前开始;-)
How interrupt works
关于java - 我如何理解 Thread.interrupt()?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14182585/