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.
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. 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. I couldn't see a way to retrieve the original Callable out of it or restore the FutureTask to a non-canceled state.
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. 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
.
Use Runnable
instead of threads. The execution pool can handle a Runnable
the same way a Thread
, but a Runnable
could be rerunned number of times.
If you want to have a return value you can use a Callable. http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Callable.html
精彩评论