Java执行者:我如何停止提交的任务?

前端之家收集整理的这篇文章主要介绍了Java执行者:我如何停止提交的任务?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经使用执行器提交了一个任务,我需要它在一段时间后停止(例如5分钟).我试过这样做:
  1. for (Future<?> fut : e.invokeAll(tasks,300,TimeUnit.SECONDS)) {
  2. try {
  3. fut.get();
  4. } catch (CancellationException ex) {
  5. fut.cancel(true);
  6. tasks.clear();
  7. } catch(ExecutionException ex){
  8. ex.printStackTrace(); //FIXME: gestita con printstack
  9. }
  10. }

但是我总是得到一个错误:我有一个共享的Vector需要被任务修改,然后被一个线程读取,即使我停止了所有的任务,如果超时发生我得到:

  1. Exception in thread "Thread-1" java.util.ConcurrentModificationException

有什么不对? 5分钟后如何停止提交的工作?

解决方法

只是因为你在Future上调用cancel()并不意味着任务会自动停止.你必须在任务中做一些工作,以确保它停止:

>使用cancel(true),以便将中断发送到任务.
>处理InterruptedException.如果您的任务中的函数抛出InterruptedException,请确保在捕获异常时尽快退出.
>如果任务执行连续计算,请定期检查Thread.currentThread().isInterrupted().

例如:

  1. class LongTask implements Callable<Double> {
  2. public Double call() {
  3.  
  4. // Sleep for a while; handle InterruptedException appropriately
  5. try {
  6. Thread.sleep(10000);
  7. } catch (InterruptedException ex) {
  8. System.out.println("Exiting gracefully!");
  9. return null;
  10. }
  11.  
  12.  
  13. // Compute for a while; check Thread.isInterrupted() periodically
  14. double sum = 0.0;
  15. for (long i = 0; i < 10000000; i++) {
  16. sum += 10.0
  17. if (Thread.currentThread().isInterrupted()) {
  18. System.out.println("Exiting gracefully");
  19. return null;
  20. }
  21. }
  22.  
  23. return sum;
  24. }
  25. }

另外,正如其他帖子所提到的那样,即使使用线程安全的Vector类,ConcurrentModificationException也可以被抛出,因为从Vector获取的迭代器不是线程安全的,因此需要同步.高级for循环使用迭代器,因此请注意:

  1. final Vector<Double> vector = new Vector<Double>();
  2. vector.add(1.0);
  3. vector.add(2.0);
  4.  
  5. // Not thread safe! If another thread modifies "vector" during the loop,then
  6. // a ConcurrentModificationException will be thrown.
  7. for (Double num : vector) {
  8. System.out.println(num);
  9. }
  10.  
  11. // You can try this as a quick fix,but it might not be what you want:
  12. synchronized (vector) { // "vector" must be final
  13. for (Double num : vector) {
  14. System.out.println(num);
  15. }
  16. }

猜你在找的Java相关文章