本文介绍了Thread.isInterrupted不起作用,Thread.interrupted起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下程序演示了该问题(最新的JVM和什么):

The following program demonstrates the problem (latest JVM & whatnot):

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();
}

推荐答案

这看起来像是多处理器计算机上的已知问题,主要是在64位OS和1.5-7.0的Java版本中

This looks like a known issue with multi-processor machines, mainly in 64-bit OS and java versions from 1.5 - 7.0

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

A DESCRIPTION OF THE PROBLEM :While running two simultaneous threads, the first thread interrupts the second one using Thread.interrupt().The second thread tests if it has been interrupted calling the Thread.isInterrupted() method which always returns false.

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

This occurs on a multiprocessor PC running a 64-Bit OS (Vista and Linux).On Vista 64-Bit, this occurs when using a 64-bit JVM (all versions from 1.5 to 1.7), but does not occur when using a 32-bit JVM.On Linux 64-bit, this occurs when using a 64-bit JVM (all versions from 1.5 to 1.7) or when using a 32-bit JVM (all versions from 1.5 to 1.7).

解决方案是使用此修补程序安装版本1.6.0_16-b02或更高版本.

The solution is to install the version with the fix, which is 1.6.0_16-b02 or later.

这篇关于Thread.isInterrupted不起作用,Thread.interrupted起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 14:15