Callable与Future的应用
来源:互联网 发布:centos安装vnc 编辑:程序博客网 时间:2024/06/06 12:05
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; public class CallableAndFuture { public static void main(String[] args) { ExecutorService threadPool = Executors.newSingleThreadExecutor(); Future<String> future = threadPool.submit( //submit 会调用Callable方法 会有返回结果 new Callable<String>() { @Override public String call() throws Exception { // TODO Auto-generated method stub Thread.sleep(2000); return "hello"; } } ); System.out.println("等待结果"); try { System.out.println("拿到结果:"+ future.get()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } ExecutorService threadPool2 = Executors.newFixedThreadPool(10); // CompletionService 用于提交一组Callable任务 CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2); for(int i = 0; i< 10 ; i++){ final int squence = i; completionService.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { // TODO Auto-generated method stub Thread.sleep(new Random().nextInt(5000)); return squence; } }); } for(int i=0; i<10; i++){ try { System.out.println(completionService.take().get()); // 先取得先运行完的线程返回的结果 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
阅读全文
0 0
- Callable与Future的应用
- Callable与Future的应用
- java 之 Callable 与 Future 的应用
- java5线程 Callable与Future的应用
- 10-Callable与Future的应用
- 【java并发】Callable与Future的应用
- Java并发:Callable与Future的应用
- Callable和Future的应用
- Callable和Future的应用
- (8)java5线程 Callable与Future的应用
- (8)java5线程 Callable与Future的应用
- Java多线程研究(七)Callable与Future的应用
- 【张孝祥并发课程笔记】09:Callable与Future的应用
- Java新技术---线程学习之Callable与Future的应用
- 线程池Executors、Callable与Future的应用
- Thread学习(五)Callable与Future的应用
- java并发编程系列之Callable与Future的应用
- Callable与Future的介绍
- iOS 证书详情介绍
- 浏览器user agent
- 详解spl_autoload_register()函数
- Vue生命周期
- cvutMatrix.h数据存储初始化及访问
- Callable与Future的应用
- 排序之插入排序
- 基本数据类型、包装类、String类型之间的相互转换
- JQuery 动态加载CSS
- PHP数组和Json之间的转换
- 安卓中不同的类之间交互,用接口比较好
- JavaScript设计模式之代理模式
- Hololens开发手记——Unity之World Anchor空间锚
- js插件获取当前所在的省市