java-引发InterruptedException时不会清除线程中断状态

有人可以解释为什么该程序打印多个“中断的”语句.

根据Thread.sleep javadoc

InterruptedException – if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Test {

    public static void main(String[] args) throws Exception {

        for (int z = 0; z < 100; z++) {

            ExecutorService executor1 = Executors.newSingleThreadExecutor();

            executor1.execute(new Runnable() {

                @Override
                public void run() {

                    ExecutorService executor2 = Executors.newFixedThreadPool(10);

                    for (int i = 0; i < 10; i++) {

                        executor2.execute(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Thread.sleep(1000 * 100);
                                } catch (InterruptedException e) {
                                    if (Thread.currentThread().isInterrupted()) {
                                        System.out.println("interrupted");
                                    }
                                }
                            }
                        });
                    }

                    executor2.shutdownNow();
                    try {
                        executor2.awaitTermination(5, TimeUnit.SECONDS);
                    } catch (InterruptedException e) {
                    }
                }
            });

            executor1.shutdown();

            try {
                executor1.awaitTermination(10, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
            }
        }
    }
}

output – screenshot

解决方法:

doc开始

If this thread is blocked in an invocation of the wait(), wait(long),
or wait(long, int) methods of the Object class, or of the join(),
join(long), join(long, int), sleep(long), or sleep(long, int), methods
of this class, then its interrupt status will be cleared and it will
receive an InterruptedException.

在Thread.sleep(1000 * 100)期间关闭执行程序服务并抛出InterruptedException时,将清除状态.

但是ThreadPoolExecutor通过t.interrupt()重置状态,因此您仍然可以获取状态.

这是重置状态的邮政编码:

    for (Worker w : workers) {
        Thread t = w.thread;
        if (!t.isInterrupted() && w.tryLock()) {
            try {
                t.interrupt();
            } catch (SecurityException ignore) {
            } finally {
                w.unlock();
            }
        }
        if (onlyOne)
            break;
    }
上一篇:视频直播点播nginx-rtmp开发手册中文版


下一篇:BATJ面试必会之并发篇