ExecutorCompletionService的使用方法
import java.util.ArrayList; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; public class Test { static class Call implements Callable<String> { String name; public Call(String name) { this.name = name; } @Override public String call() throws Exception { if (name.equals("5")) Thread.sleep(5000); Thread.sleep(1000); System.out.println(name + "over"); return name; } } public static void main(String[] args) throws Exception { ExecutorCompletionService<String> pool = new ExecutorCompletionService<String>( Executors.newFixedThreadPool(5)); ArrayList<String> list = new ArrayList<String>(); for (int i = 0; i < 10; i++) pool.submit(new Call(i + "")); for (int i = 0; i < 10; i++) { Future<String> f = pool.poll(2000, TimeUnit.MILLISECONDS);//poll函数无参数则不等待,有完成结果则返回结果,无完成结果则返回null if (null != f) { String res = f.get(); list.add(res); } else System.out.println(i + "null"); } for (int i = 0; i < list.size(); i++) System.out.println(list.get(i)); } }
执行结果:
2over
1over
3over
0over
4over
6over
7over
8over
9over
9null
2
1
3
0
4
6
7
8
9
5over