您走错了路。线程池拥有线程,并且通过与代码共享它们可以使事情搞砸。
您应该专注于 使您的任务 (传递到可取消/可中断的线程),而不是直接与池所拥有的线程进行交互。
另外,在尝试中断线程时,您将不知道正在执行什么作业,因此我看不到您为什么会对这样做感兴趣
更新:
取消线程池中提交的任务的正确方法是通过
Future执行程序返回的任务。
1)你肯定知道你真正的目的是试图任务被取消这样
2)如果你的任务已经被设计为撤销那么你有一半的方式有
3)不要使用标志来表明取消,但使用
Thread.currentThread().interrupt()替代
更新:
public class InterruptableTasks { private static class InterruptableTask implements Runnable{ Object o = new Object(); private volatile boolean suspended = false; public void suspend(){suspended = true; } public void resume(){ suspended = false; synchronized (o) { o.notifyAll(); } } @Override public void run() { while(!Thread.currentThread().isInterrupted()){ if(!suspended){//Do work here} else{//Has been suspendedtry { while(suspended){ synchronized(o){ o.wait(); } } }catch (InterruptedException e) { } } } System.out.println("Cancelled"); } } public static void main(String[] args) throws InterruptedException { ExecutorService threadPool = Executors.newCachedThreadPool(); InterruptableTask task = new InterruptableTask(); Map<Integer, InterruptableTask> tasks = new HashMap<Integer, InterruptableTask>(); tasks.put(1, task); //add the tasks and their ids Future<?> f = threadPool.submit(task); TimeUnit.SECONDS.sleep(2); InterruptableTask theTask = tasks.get(1);//get task by id theTask.suspend(); TimeUnit.SECONDS.sleep(2); theTask.resume(); TimeUnit.SECONDS.sleep(4); threadPool.shutdownNow(); }


