测试Shutdown
来源:互联网 发布:谈谈大数据金融行业应 编辑:程序博客网 时间:2024/06/05 14:13
public class TestShutdown { public static ExecutorService threadPool = Executors.newFixedThreadPool(5); public static void main(String[] args) { Long begin = System.currentTimeMillis(); //future.get()如果任务已完成,将立即返回结果,否则会阻塞当前线程,直到任务进入完成状态,然后返回结果或者抛出异常。 //所以要多线程同时运行,保存多个future的引用,待线程执行完成后再获取结果 List<Future<Integer>> list = new ArrayList<>(); for (int i = 0; i < 100; i++) { Future<Integer> c = threadPool.submit(new Work()); list.add(c); } //shutdown执行完当前正在运行的线程和已经加入队列中的任务才会关闭线程池 threadPool.shutdown(); while (true) { if (threadPool.isTerminated()) { break; } } System.out.println(list.size() + "=========="); for (Future<Integer> future : list) { try {System.out.println(future.get() + "--------------");} catch (InterruptedException e) {} catch (ExecutionException e) {} } System.out.println("end=========" + String.valueOf(System.currentTimeMillis() - begin)); } static class Work implements Callable<Integer> { @Override public Integer call() { Random r = new Random(); try {Thread.currentThread().sleep(1000);System.out.println(Thread.currentThread().getName()); } catch (InterruptedException e) {e.printStackTrace();} return r.nextInt(5000); } } }
使用CompletionService解决方案:
public class TestShutdown2 { public static ExecutorService threadPool = Executors.newFixedThreadPool(5); public static void main(String[] args) { try { Long begin = System.currentTimeMillis(); CompletionService<Integer> ecs = new ExecutorCompletionService<Integer>(threadPool); for (int i = 0; i < 100; i++) { ecs.submit(new Work()); } for (int i = 0; i < 100; ++i) { Integer r = null; try { r = ecs.take().get(); } catch (InterruptedException e) { } catch (ExecutionException e) { } if (r != null) System.out.println(r); } System.out.println("end=========" + String.valueOf(System.currentTimeMillis() - begin)); } catch (Exception e) { } finally {threadPool.shutdown();} } static class Work implements Callable<Integer> { @Override public Integer call() { Random r = new Random(); try {Thread.currentThread().sleep(1000);} catch (InterruptedException e) {e.printStackTrace();} return r.nextInt(5000); } } }
阅读全文
0 0
- 测试Shutdown
- socket之shutdown发送FIN测试
- shutdown
- Shutdown
- Shutdown
- ShutDown
- shutdown
- shutdown
- shutdown
- shutdown
- shutdown
- shutdown
- shutdown
- Shutdown
- shutdown
- shutdown
- shutdown
- shutdown()
- 【Qt 编译】QT 工程文件
- postgresql+pgrouting 最短路线sql (4)
- 频道
- Git忽略规则及.gitignore规则不生效的解决办法
- C# 判断用户是手机访问还是电脑访问
- 测试Shutdown
- jQuery选择器
- CopyFile
- lo4j简介
- 新浪云SAE部署详细图解教程
- 'gbk' codec can't decode byte 0xaf in position 6532: illegal multibyte sequence
- vue 组件回调
- 分组取每组最大的值
- 发布sql view到geoserver服务器(5)