简体   繁体   English

如何在线程池中响应取消的futuretask?

[英]How to reactive a cancelled futuretask in thread pool?

I use ThreadPoolExecutor to run some actions, at some time I cancelled some future tasks and stored it into a list to arrange some other tasks to do, and after that I want to reactive the saved cancelled future tasks. 我使用ThreadPoolExecutor来运行某些操作,有时我取消了一些未来的任务并将其存储到列表中以安排其他任务要做,之后我想要响应已保存的已取消的未来任务。

But the problem is when I submit the task into the pool, it would not be executed, looks like the cancelled or done flag is saved and recognized by the thread executor, and thus that thread would not be called. 但问题是当我将任务提交到池中时,它不会被执行,看起来像被取消或完成的标志被线程执行器保存和识别,因此不会调用该线程。

What should I do? 我该怎么办?

The FutureTask implementation maintains the canceled state. FutureTask实现维护已取消的状态。 Essentially, when the run() method is called again, it does a CAS operation which fails since the state is not runnable and returns immediately without invoking the inner Callable 's call() method. 本质上,当再次调用run()方法时,它会执行CAS操作,该操作因状态不可运行而失败并立即返回而不调用内部Callable的call()方法。 I couldn't see a way to retrieve the original Callable out of it or restore the FutureTask to a non-canceled state. 我看不到从中检索原始Callable或将FutureTask恢复到未取消状态的方法。

In response to what should you do... Do you have to cancel them? 为了回应你应该做什么...你必须取消它们吗? Why not let them run? 为什么不让他们跑? If you want priority execution, could you try creating your ThreadPoolexecutor with a PriorityBlockingQueue and use a Comparator to establish the priority. 如果您想要优先执行,您是否可以尝试使用PriorityBlockingQueue创建ThreadPoolexecutor并使用Comparator来确定优先级。 This will allow tasks to be executed in the proper order since they will be added to the PriorityBlockingQueue based on the results of the Comparator . 这将允许以适当的顺序执行任务,因为它们将根据Comparator的结果添加到PriorityBlockingQueue

Use Runnable instead of threads. 使用Runnable而不是线程。 The execution pool can handle a Runnable the same way a Thread , but a Runnable could be rerunned number of times. 执行池可以像处理Thread一样处理Runnable ,但Runnable可以重新运行多次。

If you want to have a return value you can use a Callable. 如果要获得返回值,可以使用Callable。 http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Callable.html http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Callable.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM