java - 如何用future来中断一个线程,想要通过future发出的中断来执行一些任务

标签 java multithreading future cancellation interrupted-exception

我对 Java 中的 future 和多线程很陌生。我有一个简单的问题,但结果很复杂,我有许多线程(其中都有打开的 session ),它们是无限打开的。每当一个线程抛出自定义异常( session 超时异常)时,我就必须中断所有线程并正常关闭所有 session 。我所做的就是存储线程返回的 future 对象(在 ArrayList 中)并循环遍历它,并在一个线程抛出异常时为所有对象发出 future.cancel 。

private static void futureCancel()
{
        for(int i=0;i<numberStreams;i++)
        {
            Future<String> future=futureList.get(i);
            try{
                future.cancel(true);
                future.get();
            }
            catch(InterruptedException e)
            {
                System.out.println("In interrupted block!");
            } catch (ExecutionException e) {
                e.printStackTrace();
            }       
        }
        return;
    }

这里的问题是,由于一些要求问题以及 session 另一端的工作方式,我无法在线程代码中添加 InterruptedException。如果我从可调用对象中抛出 InterruptedException,它不会到达上面指定的 catch block 。如果我在线程中添加 sleep (可以进行测试)并处理 InterruptedException,那么一旦发出 future.cancel,它就会进入该 block 。我做错了什么?

最佳答案

Futuer#cancel(boolean) javadoc

This attempt will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.

所以要么 ExecutorService尚未执行Runnable/Callable并可以将其从队列中删除,或者它具有 ExecutorService必须调用Thread#interrupt()和你的Runnable/Callable代码必须处理它。

没有其他方法可以通过 Future中断线程的接口(interface)。如果您Runnable没有办法处理中断,那么可能会发生很多事情。如果 InterruptedException发生时,它会冒泡到 ExecutorService并被包裹在 ExecutionException 中将从 Future#get() 抛出。如果没有InterruptedException发生在执行 Runnable 的线程中,你的Runnable将继续不受阻碍。

你真的应该考虑改变你的 Runnable处理中断。

关于java - 如何用future来中断一个线程,想要通过future发出的中断来执行一些任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21586586/

相关文章:

java - Google端点java Oauth/Oauth2完整示例

java - Fitnesse 上的定制 fixture

java - AppEngine 开发服务器 - 并发任务限制

Java future : get the time per request

Java 文件 IO 和 "access denied"错误

java - Java中的多线程: how to transfer funds between accounts correctly?

c++ - GCC 8.1.0/MinGW64 编译的 OpenMP 程序崩溃寻找 cygwin.s?

c++ - SignalObjectAndWait 考虑有 SetEvent 和 WaitForSingleObject 的目的是什么?

scala - 在 Scala 中使用 Future 和 Promise 取消

java - 理解 Java Completablefuture 的行为