Callable&&Future的基本使用
2015-12-01 14:56
405 查看
ExecutorService的submit
ExecutorService的submit方法可以接收一个Callable<T>对象,并且返回一个Future<V> 。public interface Callable<V> { /** * Computes a result, or throws an exception if unable to do so. * * @return computed result * @throws Exception if unable to compute a result */ V call() throws Exception; }
public interface Future<V> { //取消执行的任务 boolean cancel(boolean mayInterruptIfRunning); //如果任务在未完成之前取消,则返回true boolean isCancelled(); //任务完成,返回true boolean isDone(); // 等待返回的结果 V get() throws InterruptedException, ExecutionException; //按照指定的时间去获取执行的结果, V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }
class MyCallable1 implements Callable<String> { public String call() throws Exception { return " method call is running"; }; } @Test public void test01() throws Exception { // 1、创建线程池 ExecutorService threadPool = Executors.newSingleThreadExecutor(); // 2、提交任务、获取返回值 Future<String> future = threadPool.submit(new MyCallable1()); //3、输出返回值 System.out.println(future.get()); threadPool.shutdown(); }
CompletionService
可以提交一组Callable,并使用take方法返回已完成一个Callable任务对应的Future对象。class MyCallable2 implements Callable<Integer> { private int seq ; public MyCallable2(int seq){ this.seq = seq; } @Override public Integer call() throws Exception { Thread.sleep(new Random().nextInt(5000)); return seq; } } @Test public void test02() throws Exception { ExecutorService threadPool2 = Executors.newFixedThreadPool(10); CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2); for (int i = 1; i <= 10; i++) { completionService.submit(new MyCallable2(i)); } for (int i = 0; i < 12; i++) { System.out.println("start >> "+i); System.out.println(completionService.take().get()); System.out.println("end >> "+i); //如果没有拿到结果,会阻塞在那里。 } threadPool2.shutdown(); }
相关文章推荐
- Jquery查找选中的checkbox
- 基于jQuery实现网页打印功能
- 调用系统下载工具下载网络上的资源
- 浅谈IOC--说清楚IOC是什么
- 解决LinearLayout排版问题
- C++编程技能(经常修改)
- Input system (输入子系统)
- 转:java 看好的一些书
- Java中Runnable和Thread的区别
- html5有关地理定位
- libcurl的get、post、download的类
- ajax的分页分页请求,通过ajax来分页
- Fragment not attached to Activity 异常
- repeater绑定时获取HTML形式的控件
- drbd数据同步实施方法
- UNIX进程间的通信 FIFO
- 动手写批量邮件发送器
- ASP.NET MVC 6 一些不晓得的写法
- 信息安全系统设计基础实验四—20135214万子惠20135227黄晓妍
- bootstrap快速入门笔记(六)-代码