包样本;如何取消执行者的运行任务
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)可能会失败的情况是什么?
至少有一半不需要这里的代码或什么都不做。你可以简化这个例子,使它更容易理解。 –