Callable&&Future的基本使用
来源:互联网 发布:腾讯视频上传网络异常 编辑:程序博客网 时间:2024/03/29 16:33
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";};}@Testpublic 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;}@Overridepublic Integer call() throws Exception {Thread.sleep(new Random().nextInt(5000));return seq;}}@Testpublic 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();}
0 0
- Callable&&Future的基本使用
- callable&future的使用
- Callable和future的使用
- Future接口和Callable接口的使用
- Java—Callable,Future的使用
- Java的Callable和Future使用
- Callable和Future、FutureTask的使用
- Callable和Future、FutureTask的使用
- Callable和Future、FutureTask的使用
- Java Callable Future 使用
- Callable和Future使用
- Callable 和Future 接口使用
- java中的Callable和Future的使用和困惑
- java多线程Future和Callable类的解释与使用
- Callable和Future结合使用的一个例子
- java 使用Callable和Future返回线程执行的结果
- Java并发编程实践之Callable,Future,RutureTask的使用
- 高级并发编程学习-callable与Future的使用
- Java中Runnable和Thread的区别
- 浅谈IOC--说清楚IOC是什么
- 调用系统下载工具下载网络上的资源
- Android 详解实现TextView加载带图片标签的Html并按比例缩放
- Jquery查找选中的checkbox
- Callable&&Future的基本使用
- 解决【2006 - MySQL server has gone away】问题
- android MVP架构
- 循环结构的程序设计
- C-016.#include预编译处理,可用于多文件开发
- UIView动画的具体用法
- os发展史
- Source Insight乱码的解决方案,SI不支持UTF-8字符编码乱码
- AndroidManifest.xml 配置文件