简体   繁体   中英

How to cancel the running task of executor

package sample;

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) {

  }
}
}

In the cancel method, running tasks are not getting cancelled. Any way to cancel the running task even if the thread is sleeping i wanted to interrupt the thread from sleep and kill the entire task?

What are the situations in which cancel(true) may fail?

What you need is List<Future<?>> self ; problem in your code is that you are overriding self on every submit whereas on submit Future return needs to be kept separately.

Also change your waitAndSweep method:

self.add(threadPoolExecutor.submit(timerTask))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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