Java ExecutorService暂停/恢复一个特定的线程
发布时间:2020-12-14 16:37:44 所属栏目:Java 来源:网络整理
导读:有没有办法使用ExecutorService来暂停/恢复一个特定的线程? private static ExecutorService threadpool = Executors.newFixedThreadPool(5); 想象一下,我想停止线程,因为id = 0(假设每个线程被分配一个增量的id,直到达到线程池的大小). 过了一会儿,按一下
有没有办法使用ExecutorService来暂停/恢复一个特定的线程?
private static ExecutorService threadpool = Executors.newFixedThreadPool(5); 想象一下,我想停止线程,因为id = 0(假设每个线程被分配一个增量的id,直到达到线程池的大小). 过了一会儿,按一下按钮,我想恢复那个特定的线程,并把所有其他的线程当前的状态保留下来,这些线程可以暂停或恢复. 我在Java文档中找到了一个未完成的PausableThreadPoolExecutor版本.但是它不适合我需要的,因为它恢复了池中的所有线程. 如果没有办法使用ExecutorService的默认实现,任何人都可以指出这个问题的Java实现? 谢谢! 解决方法
你在错误的轨道上.线程池拥有线程,并通过与你的代码共享它们可能会让事情变得更糟.
您应该专注于使您的任务(传递到线程可撤销/可中断),而不是直接与池拥有的线程进行交互. 此外,您不知道在尝试中断线程时执行什么工作,所以我不明白为什么你会对此感兴趣 更新: 更新: 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 suspended try { while(suspended){ synchronized(o){ o.wait(); } } } catch (InterruptedException e) { } } } System.out.println("Cancelled"); } } /** * @param args * @throws InterruptedException */ 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(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |