线程池Executors、Callable与Future的应用
2016-08-10 17:09
441 查看
package cn.itcast.heima; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * Callable与Future的应用 * @ClassName: CallableAndFuture * @Description: TODO * @author honghao * @date 2016年8月10日 下午4:24:33 */ public class CallableAndFuture { public static void main(String[] args) { ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<String> future = executorService.submit(new Callable<String>() { @Override public String call() throws Exception { Thread.sleep(1000); return "hello"; } }); try { System.out.println("等待结果"); System.out.println(future.get()); executorService.shutdown(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } ExecutorService executorService2 = Executors.newFixedThreadPool(10); CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>( executorService2); for (int i = 0; i < 10; i++) { final int seq = i; completionService.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { return seq; } }); } for (int i = 0; i < 10; i++) { try { Thread.sleep(new Random().nextInt(3000)); System.out.println(completionService.take().get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } executorService.shutdown(); executorService2.shutdown(); } }
相关文章推荐
- java多线程并发库高级应用 之 java5中的线程并发库--线程池、Callable&Future
- 多线程并发库高级应用 之 java5中的线程并发库--线程池、Callable&Future
- 多线程并发库高级应用 之 java5中的线程并发库--线程池、Callable&Future
- 多线程并发库高级应用 之 java5中的线程并发库--线程池、Callable&Future
- JAVA线程池之ExecutorService Future Callable Submit简单应用
- 10-Callable与Future的应用
- 【重点:线程池续】超人气组合:Callable和Future
- (8)java5线程 Callable与Future的应用
- 【张孝祥并发课程笔记】09:Callable与Future的应用
- 线程池 submit 方法结合 Callable Future 的使用
- Java多线程编程--(8)学习Java5.0 并发编程包--线程池、Callable & Future 简介
- 线程池的使用Executors和Future
- 线程池 Executors工具应用
- Java:多线程,线程池,使用CompletionService通过Future来处理Callable的返回结果
- 黑马程序员——Java5中的线程并发库(一)---概述、线程池、Callable和Future、Lock和Condition
- Java多线程与并发库高级应用之Callable和Future
- 线程池中Executors应用(一)
- (8)java5线程 Callable与Future的应用
- NO.10 Callable与Future的应用
- Java 7之多线程线程池 - Callable和Future