Callable与Future的应用得到线程的返回结果(十)

来源:互联网 发布:软件下载页面打不开 编辑:程序博客网 时间:2024/06/06 07:36

获取一个线程的运行结果

public interface Callable<V>

返回结果并且可能抛出异常的任务。实现者定义了一个不带任何参数的叫做call 的方法。 Callable 接口类似于Runnable,两者都是为那些其实例可能被另一个线程执行的类设计的。但是Runnable 不会返回结果,并且无法抛出经过检查的异常。

只有一个方法Vcall() 计算结果,如果无法计算结果,则抛出一个Exception异常。

使用方法:

       ExecutorServicethreadPool = Executors.newSingleThreadExccutor();

       如果不需要返回结果,就用executor方法 调用submit方法返回一个Future对象

       Future<T> future = threadPool.submit(new Callable<T>(){//接收一个Callable接口的实例对象

                     覆盖Callable接口中的call方法,抛出异常

                     publicTcall() throws Exception

                     {

                            ruturnT

}

});

获取Future接收的结果

future。get();会抛出异常

future.get()没有拿到结果就会一直等待

       Future取得的结果类型和Callable返回的结果类型必须一致,通过泛型实现。Callable要通过ExecutorService的submit方法提交,返回的Future对象可以取消任务。

 

public interface Future<V>

Future 表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并获取计算的结果。计算完成后只能使用get 方法来获取结果,如有必要,计算完成前可以阻塞此方法。取消则由cancel 方法来执行。还提供了其他方法,以确定任务是正常完成还是被取消了。一旦计算完成,就不能再取消计算。如果为了可取消性而使用Future 但又不提供可用的结果,则可以声明Future<?> 形式类型、并返回 null 作为底层任务的结果。

方法摘要

 boolean

cancel(boolean mayInterruptIfRunning)           试图取消对此任务的执行。

 V

get()           如有必要,等待计算完成,然后获取其结果。

 V

get(long timeout,TimeUnit unit)           如有必要,最多等待为使计算完成所给定的时间之后,获取其结果(如果结果可用)。

 boolean

isCancelled()           如果在任务正常完成前将其取消,则返回 true。

 boolean

isDone()           如果任务已完成,则返回 true。


public interface CompletionService<V>

       CompletionService用于提交一组Callable任务,其take方法返回一个已完成的Callable任务对应的Future对象。好比同时种几块麦子等待收割,收割时哪块先熟先收哪块。

将生产新的异步任务与使用已完成任务的结果分离开来的服务。生产者submit 执行的任务。使用者 take 已完成的任务,并按照完成这些任务的顺序处理它们的结果。例如,CompletionService 可以用来管理异步 IO ,执行读操作的任务作为程序或系统的一部分提交,然后,当完成读操作时,会在程序的不同部分执行其他操作,执行操作的顺序可能与所请求的顺序不同。

通常,CompletionService 依赖于一个单独的 Executor 来实际执行任务,在这种情况下,CompletionService 只管理一个内部完成队列。ExecutorCompletionService 类提供了此方法的一个实现。

CompletionService方法摘要

 Future<V>

poll()           获取并移除表示下一个已完成任务的 Future,如果不存在这样的任务,则返回 null。

 Future<V>

poll(long timeout,TimeUnit unit)          获取并移除表示下一个已完成任务的 Future,如果目前不存在这样的任务,则将等待指定的时间(如果有必要)。

 Future<V>

submit(Callable<V> task)           提交要执行的值返回任务,并返回表示挂起的任务结果的 Future。

 Future<V>

submit(Runnable task,V result)           提交要执行的 Runnable 任务,并返回一个表示任务完成的 Future,可以提取或轮询此任务。

 Future<V>

take()           获取并移除表示下一个已完成任务的 Future,如果目前不存在这样的任务,则等待。

ExecutorCompletionService构造方法摘要

ExecutorCompletionService(Executor executor)
          使用为执行基本任务而提供的执行程序创建一个 ExecutorCompletionService,并将 LinkedBlockingQueue 作为完成队列。

 

ExecutorCompletionService(Executor executor,BlockingQueue<Future<V>> completionQueue)
          使用为执行基本任务而提供的执行程序创建一个 ExecutorCompletionService,并将所提供的队列作为其完成队列。

 

示例:

ExecutorService threadPool = Executors.newFixedThreadPool(10);   //创建线程池,传递给coms

       用threadPool执行任务,执行的任务返回结果都是整数

CompletionService<Integer> coms = newExecutorCompletionService<Integer>(threadPool);

       提交10个任务  种麦子

for (int i=0; i<10; i++)

{

       finalint num = i+1;

coms.submit(newCallable<Integer>(){

public Integercall()       覆盖call方法

{匿名内部类使用外部变量要用final修饰

       SOP(任务+num);

       Thread.sleep(newRandom().nextInt(6)*1000);

       return num;

}

});

}

       等待收获       割麦子

for (int i=0; i<10; i++)

{     take获取第一个Future对象,用get获取结果

       SOP(coms.take().get());

}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

public class CallableAndFuture {


    /**
     * @param args
     */
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        Future<String> future = threadPool.submit(new Callable<String>() {
            public String call() throws Exception {
                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 (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("等待结果--------");
        ExecutorService threadPool2 = Executors.newFixedThreadPool(10);
        CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2);
        for (int i = 1; i <= 10; i++) {
            final int seq = i;
            completionService.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    Thread.sleep(new Random().nextInt(5000));
                    return seq;
                }
            });
        }
        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 (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }


}


0 0
原创粉丝点击