栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java ExecutorService暂停/恢复特定线程

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java ExecutorService暂停/恢复特定线程

您走错了路。线程池拥有线程,并且通过与代码共享它们可以使事情搞砸。
您应该专注于 使您的任务 (传递到可取消/可中断的线程),而不是直接与池所拥有的线程进行交互。
另外,在尝试中断线程时,您将不知道正在执行什么作业,因此我看不到您为什么会对这样做感兴趣

更新:
取消线程池中提交的任务的正确方法是通过

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();          }


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/451330.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号