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
原创粉丝点击