如何取消执行程序的运行任务

时间:2015-10-05 12:40:07

标签: java multithreading

包装样品;

import java.util.TimerTask;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolExecutorEg {
  TimerTask timerTask;
  int  oneThread       = 1;
  long zeroKeepAlive   = 0L;
  int  queueDepthOfOne = 1;

  ThreadPoolExecutor threadPoolExecutor =
        new ThreadPoolExecutor(
              oneThread,
              oneThread,
              zeroKeepAlive,
              TimeUnit.MILLISECONDS,
              new ArrayBlockingQueue<Runnable>(queueDepthOfOne)
        );
  private volatile static Future<?> self;
public static void main(String args[]){
  ThreadPoolExecutorEg myTimer = new ThreadPoolExecutorEg();
  myTimer.waitAndSweep("A");
  myTimer.waitAndSweep("B");

  cancel();
  myTimer.waitAndSweep("replace");
  myTimer.waitAndSweep("B");

}

private static void cancel() {
self.cancel(true); 
System.out.println(self.isCancelled());
}

public void waitAndSweep(final String caller) {
  try { 


      timerTask = new TimerTask() {

        @Override
        public void run() {
          try {
          long waitTime = 1000;
            if (waitTime > 0){
              Thread.sleep(waitTime);
            }

          } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
          System.out.println(caller);
        }
      };

    self = threadPoolExecutor.submit(timerTask);


  }catch(RejectedExecutionException re){
System.out.println(re);
  }
  catch (Exception e) {

  }
}
}

在取消方法中,运行任务不会被取消。即使线程处于休眠状态,任何取消正在运行的任务的方法我想从睡眠中断线程并终止整个任务?

取消(true)可能失败的情况是什么?

1 个答案:

答案 0 :(得分:0)

您需要的是List<Future<?>> self;您的代码中的问题是,您在self上覆盖submit,而在submit Future返回时需要单独保留。

同时更改waitAndSweep方法:

self.add(threadPoolExecutor.submit(timerTask))