包樣本;如何取消執行者的運行任務
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)可能會失敗的情況是什麼?
至少有一半不需要這裏的代碼或什麼都不做。你可以簡化這個例子,使它更容易理解。 –