ExecutorService为什么不能中断线程?

Why thread can't be interrupted in ExecutorService?

我做了一个简单的测试,代码如下:

    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?不对 ?因为当前池中只有一个线程,它应该在第一个任务中被中断,为什么第二个任务运行s时它仍然可用(未被中断)?

提前致谢!

另一个问题是我修改 运行 函数如下:

    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 从睡眠中唤醒。但是当我使用 Thread.currentThread().isInterrupted() 检查它时,它仍然是 return false.

sleep()会吃掉中断状态吗??

查看ThreadPoolExecutor的源代码,有一个名为clearInterruptsForTaskRun的私有方法记录为:

Ensures that unless the pool is stopping, the current thread does not have its interrupt set