TA的每日心情 | 开心 2021-12-13 21:45 |
---|
签到天数: 15 天 [LV.4]偶尔看看III
|
在ExecutorService的submit方法中可以获取返回值,通过Future的get方法,但是这个Future类存在缺陷,Future接口调用get()方法取得处理后的返回结果时具有阻塞性,也就是说调用Future的get方法时,任务没有执行完成,则get方法要一直阻塞等到任务完成为止。
这样大大的影响了系统的性能,这就是Future的最大缺点。为此,java1.5以后提供了CompletionServlice来解决这个问题。
CompletionService
接口CompletionService的功能是异步的方式,一边生产任务,一边处理完成的任务结果,这样可以将执行的任务与处理任务隔离开来进行处理,使用submit执行任务,使用塔克获取已完成的任务,并按照这些任务的完成的时间顺序来处理他们的结果。
如图这个是CompletionService的核心方法
其有构造器如下;- [code] CompletionService<T> completionService=new ExecutorCompletionService<T>(executorService);
复制代码 [/code]可以发现,需要传入一个executor,
下面demo来解释CompletionService解决Future的缺点。
首先创建一个类- [code]package com.completion;
- import java.util.concurrent.Callable;
- public class MyCallable implements Callable<String>{
- private String name;
- private long sleep;
- public MyCallable(String name,long sleep) {
- super();
- this.name=name;
- this.sleep=sleep;
- }
- @Override
- public String call() throws Exception {
- Thread.sleep(sleep);
- return "call()---->"+name;
- }
- }
复制代码 [/code]测试方法- [code]package com.completion;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.concurrent.Callable;
- import java.util.concurrent.CompletionService;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.Executor;
- import java.util.concurrent.ExecutorCompletionService;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import javax.annotation.processing.Completion;
- public class Test {
- public static void main(String[] args) throws InterruptedException, ExecutionException {
- //模拟不同的耗时
- MyCallable callable=new MyCallable("小double", 1000);
- MyCallable callable1=new MyCallable("大double", 4000);
- MyCallable callable2=new MyCallable("中double", 3000);
- List<Callable<String>>list=new ArrayList<>();
- list.add(callable);
- list.add(callable1);
- list.add(callable2);
- ExecutorService executorService=Executors.newCachedThreadPool();
- CompletionService<String>completionService=new ExecutorCompletionService<>(executorService);
- for (Callable<String>ca:list) {
- completionService.submit(ca);
- }
- for (Callable<String>ca:list) {
- System.out.println("-------------");
- System.err.println(completionService.take().get());
- }
- }
- }
复制代码 [/code]运行效果
如此一来,,,,哈哈!Android的mvp你懂得!!!! $(function () { $("pre.prettyprint code").each(function () { var lines = $(this).text().split("\n").length; var $numbering = $("").addClass("pre-numbering").hide(); $(this).addClass("has-numbering").parent().append($numbering); for (i = 1; i ").text(i)); }; $numbering.fadeIn(1700); }); }); |
|