我做了一个简单的测试,代码如下:
public class InterruptTest
{
public static class MyTask implements Runnable {
@Override
public void run() {
System.out.println("before sleep " + Thread.currentThread().isInterrupted());
System.out.println(Thread.currentThread());
Thread.currentThread().interrupt();
System.out.println("after sleep " + Thread.currentThread().isInterrupted());
}
}
public static void main(String[] str)
{
ExecutorService service = Executors.newFixedThreadPool(1);
// MyTask task1 = new MyTask();
Future<?> future1 = service.submit(new InterruptTest.MyTask());
Future<?> future2 = service.submit(new InterruptTest.MyTask());
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
System.out.println("interrupted;");
}
}
}
输出是:
before sleep false
Thread[pool-1-thread-1,5,main]
after sleep true
**before sleep false** // line 4
Thread[pool-1-thread-1,5,main]
after sleep true
为什么第4行仍然输出 false ?不对 ?因为当前池中只有一个线程,并且它应该在第一个任务中被中断,为什么当第二个任务运行时它仍然可用(没有中断)?
提前致谢!
另一个问题是我修改 run 函数如下:
public static class MyTask implements Runnable {
@Override
public void run() {
System.out.println("before sleep " + Thread.currentThread().isInterrupted());
System.out.println(Thread.currentThread());
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
System.out.println("interrupted;");
System.out.println("after sleep " + Thread.currentThread().isInterrupted());
System.out.println(Thread.currentThread());
}
}
}
一个任务的输出是:
before sleep false
Thread[pool-1-thread-1,5,main]
interrupted;
after sleep false
任务应该通过thread.interrupt从 sleep 中唤醒。但是当我使用 Thread.currentThread().isInterrupted() 检查它时,它仍然返回 false。
sleep()会吃掉中断状态吗?
最佳答案
查看ThreadPoolExecutor
的源码,有一个私有(private)方法,名为clearInterruptsForTaskRun
记录为:
Ensures that unless the pool is stopping, the current thread does not have its interrupt set
关于java - 为什么ExecutorService中的线程不能被中断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29664324/