多线程返回值,避免阻塞提高效率。
public class CallableDemo1<V> implements Callable<V> {
List<String> list=new ArrayList<String>();
@Override
public V call() throws Exception {
Thread.sleep(10000);
System.out.println("CallableDemo1 begin");
for(int i=0;i<5;i++){
list.add(Math.random()+"");
}
System.out.println("CallableDemo1 end");
// System.out.println(Thread1Test.ct);
// Thread1Test.ct.countDown();
return (V) list;
}
}
public class CallableDemo2<V> implements Callable<V> {
List<String> list=new ArrayList<String>();
@Override
public V call() throws Exception {
Thread.sleep(7000);
System.out.println("CallableDemo2 begin");
for(int i=0;i<5;i++){
Date date=new Date();
list.add(Math.random()+"");
}
System.out.println("CallableDemo2 end");
// Thread1Test.ct.countDown();
return (V) list;
}
}
普通线程池阻塞获取结果,测试结果
测试代码:
public void testCoutDown() throws InterruptedException, ExecutionException {
ExecutorService exec = Executors.newCachedThreadPool();//工头
Future<List<String>> result1=exec.submit(new CallableDemo1());
Future<List<String>> result2=exec.submit(new CallableDemo2());
long start=System.currentTimeMillis();
System.out.println(result1.get());
System.out.println((System.currentTimeMillis()-start)+"T1开始处理");
System.out.println(result2.get());
System.out.println("T2开始处理"+(System.currentTimeMillis()-start));
}
使用CompletionService非阻塞获取结果,测试结果:
测试代码:
public void testComplete() throws InterruptedException, ExecutionException{
ExecutorService exec = Executors.newCachedThreadPool();//工头
CompletionService<List<String>> service = new ExecutorCompletionService(exec);
service.submit(new CallableDemo1());
service.submit(new CallableDemo2());
System.out.println("获取结果");
long start = System.currentTimeMillis();
for(int i=0;i<2;i++){
List<String> list1 = service.take().get();
System.out.println(list1+"\n"+(System.currentTimeMillis()-start)+"线程"+i +"开始处理");
}
System.out.println("所有线程结束"+(System.currentTimeMillis()-start));
}
非阻塞获取,哪个线程先返回,哪个线程就先处理。而阻塞处理返回结果时候,是串行处理。