Java Executors:如何停止提交的任务?

Raf*_*ffo 12 java multithreading executorservice

我已经使用执行程序提交了一个任务,我需要它在一段时间后停止(例如5分钟).我试过这样做:

   for (Future<?> fut : e.invokeAll(tasks, 300, TimeUnit.SECONDS)) {
         try {
             fut.get(); 
         } catch (CancellationException ex) {
             fut.cancel(true);   
             tasks.clear();
         } catch(ExecutionException ex){
             ex.printStackTrace(); //FIXME: gestita con printstack       
         }
   }
Run Code Online (Sandbox Code Playgroud)

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

Exception in thread "Thread-1" java.util.ConcurrentModificationException
Run Code Online (Sandbox Code Playgroud)

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

Mat*_*man 24

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

  • 使用cancel(true)以便向任务发送中断.
  • 处理InterruptedException.如果任务中的某个函数抛出一个函数,请InterruptedException确保在捕获异常时尽快正常退出.
  • 定期检查Thread.currentThread().isInterrupted()任务是否进行连续计算.

例如:

class LongTask implements Callable<Double> {
    public Double call() {

         // Sleep for a while; handle InterruptedException appropriately
         try {
             Thread.sleep(10000);
         } catch (InterruptedException ex) {
             System.out.println("Exiting gracefully!");
             return null;
         }


         // Compute for a while; check Thread.isInterrupted() periodically
         double sum = 0.0;
         for (long i = 0; i < 10000000; i++) {
             sum += 10.0
             if (Thread.currentThread().isInterrupted()) {
                 System.out.println("Exiting gracefully");
                 return null;
             }
         }

         return sum;
    } 
}
Run Code Online (Sandbox Code Playgroud)

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

final Vector<Double> vector = new Vector<Double>();
vector.add(1.0);
vector.add(2.0);

// Not thread safe!  If another thread modifies "vector" during the loop, then
// a ConcurrentModificationException will be thrown.
for (Double num : vector) {
    System.out.println(num);
}

// You can try this as a quick fix, but it might not be what you want:
synchronized (vector) {    // "vector" must be final
    for (Double num : vector) {
        System.out.println(num);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 首先,调用future.cancel(true)绝对没有任何意义.invokeAll的契约声明它将在返回之前取消任务,并且实现使用最后一个块来确保它.其次,不要调用Thread.interrupted(),这样做会清除线程的中断状态.大多数实现都希望使用Thread.isInterrupted().应仔细审查清除旗帜.第三,他不必处理InterruptedException,除非他使用阻塞方法,如锁定获取,然后编译器确保他是.FutureTask将捕获异常. (7认同)