java - Thread.isInterrupted 不起作用,Thread.interrupted 起作用

标签 java multithreading interrupted-exception

下面的程序演示了这个问题(最新的 JVM 等等):

public static void main(String[] args) throws InterruptedException {
    // if this is true, both interrupted and isInterrupted work
    final boolean withPrint = false;

    // decide whether to use isInterrupted or interrupted.
    // if this is true, the program never terminates.
    final boolean useIsInterrupted = true;

    ExecutorService executor = Executors.newSingleThreadExecutor();
    final CountDownLatch latch = new CountDownLatch(1);
    Callable<Void> callable = new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            Random random = new Random();
            while (true) {
                if (withPrint) {
                    System.out.println(random.nextInt());
                    System.out.flush();
                }
                if (useIsInterrupted)
                {
                    if (Thread.currentThread().isInterrupted())
                        break;
                }
                else
                {
                    if (Thread.interrupted())
                        break;
                }
            }
            System.out.println("Nice shutdown");
            latch.countDown();
            return null;
        }
    };
    System.out.println("Task submitted");
    Future<Void> task = executor.submit(callable);
    Thread.sleep(100);
    task.cancel(true);
    latch.await();
    System.out.println("Main exited");
    executor.shutdown();
}

最佳答案

这看起来像一个 known issue多处理器机器,主要是 64 位操作系统和 1.5 - 7.0 的 java 版本

问题描述: 在同时运行两个线程时,第一个线程使用 Thread.interrupt() 中断第二个线程。 第二个线程测试它是否被中断调用 Thread.isInterrupted() 方法,该方法总是返回 false。

这发生在运行 64 位操作系统(Vista 和 Linux)的多处理器 PC 上。 在 Vista 64 位上,使用 64 位 JVM(从 1.5 到 1.7 的所有版本)时会发生这种情况,但在使用 32 位 JVM 时不会发生。 在 Linux 64 位上,使用 64 位 JVM(从 1.5 到 1.7 的所有版本)或使用 32 位 JVM(从 1.5 到 1.7 的所有版本)时会发生这种情况。

解决方案是安装修复后的版本,即 1.6.0_16-b02 或更高版本。

关于java - Thread.isInterrupted 不起作用,Thread.interrupted 起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2012259/

相关文章:

java - 如何将 java 用于每个带有自定义类的循环?

java - 使用 JAVA 控制台应用程序从桌面访问文本文件

multithreading - Matlab多核

c - 使用消息队列的 C 生产者/消费者中的段错误

java - 要么重新中断此方法,要么重新抛出声纳中的“InterruptedException 问题”

java - 使用枚举来清晰地表示错误消息——这是好的做法吗?

java - Chrome 参数不起作用

java - 如果在 sleep 线程上调用interrupt()会发生什么?

c++ - 为什么要将 mutex 作为参数传递给线程调用的函数?

java - JVM catch InterruptedException 时是否需要退出