为什么线程不能在ExecutorService中被中断?

时间:2015-04-16 02:26:43

标签: java multithreading concurrency 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行仍然输出错误?不对 ?因为当前池中只有一个线程,它应该在第一个任务中被中断,为什么它在第二个任务运行时仍然可用(不中断)?

提前致谢!

另一个问题是我修改了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从睡眠中唤醒。但是当我使用Thread.currentThread()。isInterrupted()来检查它时,它仍然返回false。

将sleep()吃掉中断状态??

1 个答案:

答案 0 :(得分:4)

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

  

确保除非池正在停止,否则当前线程没有设置其中断

相关问题