Java利用future及时获取多线程运行结果
Future接口是Java标准API的一部分,在java.util.concurrent包中。Future接口是Java线程Future模式的实现,可以来进行异步计算。
有了Future就可以进行三段式的编程了,1.启动多线程任务2.处理其他事3.收集多线程任务结果。从而实现了非阻塞的任务调用。在途中遇到一个问题,那就是虽然能异步获取结果,但是Future的结果需要通过isdone来判断是否有结果,或者使用get()函数来阻塞式获取执行结果。这样就不能实时跟踪其他线程的结果状态了,所以直接使用get还是要慎用,最好配合isdone来使用。
这里有一种更好的方式来实现对任意一个线程运行完成后的结果都能及时获取的办法:使用CompletionService,它内部添加了阻塞队列,从而获取future中的值,然后根据返回值做对应的处理。一般future使用和CompletionService使用的两个测试案例如下:
importjava.util.ArrayList; importjava.util.List; importjava.util.Random; importjava.util.concurrent.Callable; importjava.util.concurrent.ExecutorService; importjava.util.concurrent.Executors; importjava.util.concurrent.Future; /** *多线程执行,异步获取结果 * *@authori-clarechen * */ publicclassAsyncThread{ publicstaticvoidmain(String[]args){ AsyncThreadt=newAsyncThread(); List>futureList=newArrayList >(); t.generate(3,futureList); t.doOtherThings(); t.getResult(futureList); } /** *生成指定数量的线程,都放入future数组 * *@paramthreadNum *@paramfList */ publicvoidgenerate(intthreadNum,List >fList){ ExecutorServiceservice=Executors.newFixedThreadPool(threadNum); for(inti=0;i f=service.submit(getJob(i)); fList.add(f); } service.shutdown(); } /** *otherthings */ publicvoiddoOtherThings(){ try{ for(inti=0;i<3;i++){ System.out.println("dothingno:"+i); Thread.sleep(1000*(newRandom().nextInt(10))); } }catch(InterruptedExceptione){ e.printStackTrace(); } } /** *从future中获取线程结果,打印结果 * *@paramfList */ publicvoidgetResult(List >fList){ ExecutorServiceservice=Executors.newSingleThreadExecutor(); service.execute(getCollectJob(fList)); service.shutdown(); } /** *生成指定序号的线程对象 * *@parami *@return */ publicCallable getJob(finalinti){ finalinttime=newRandom().nextInt(10); returnnewCallable (){ @Override publicStringcall()throwsException{ Thread.sleep(1000*time); return"thread-"+i; } }; } /** *生成结果收集线程对象 * *@paramfList *@return */ publicRunnablegetCollectJob(finalList >fList){ returnnewRunnable(){ publicvoidrun(){ for(Future future:fList){ try{ while(true){ if(future.isDone()&&!future.isCancelled()){ System.out.println("Future:"+future +",Result:"+future.get()); break; }else{ Thread.sleep(1000); } } }catch(Exceptione){ e.printStackTrace(); } } } }; } }
运行结果打印和future放入列表时的顺序一致,为0,1,2:
dothingno:0 dothingno:1 dothingno:2 Future:java.util.concurrent.FutureTask@68e1ca74,Result:thread-0 Future:java.util.concurrent.FutureTask@3fb2bb77,Result:thread-1 Future:java.util.concurrent.FutureTask@6f31a24c,Result:thread-2
下面是先执行完的线程先处理的方案:
importjava.util.Random; importjava.util.concurrent.BlockingQueue; importjava.util.concurrent.Callable; importjava.util.concurrent.CompletionService; importjava.util.concurrent.ExecutionException; importjava.util.concurrent.ExecutorCompletionService; importjava.util.concurrent.ExecutorService; importjava.util.concurrent.Executors; importjava.util.concurrent.Future; importjava.util.concurrent.LinkedBlockingDeque; publicclasstestCallable{ publicstaticvoidmain(String[]args){ try{ completionServiceCount(); }catch(InterruptedExceptione){ e.printStackTrace(); }catch(ExecutionExceptione){ e.printStackTrace(); } } /** *使用completionService收集callable结果 *@throwsExecutionException *@throwsInterruptedException */ publicstaticvoidcompletionServiceCount()throwsInterruptedException,ExecutionException{ ExecutorServiceexecutorService=Executors.newCachedThreadPool(); CompletionServicecompletionService=newExecutorCompletionService ( executorService); intthreadNum=5; for(inti=0;i getTask(finalintno){ finalRandomrand=newRandom(); Callable task=newCallable (){ @Override publicIntegercall()throwsException{ inttime=rand.nextInt(100)*100; System.out.println("thead:"+no+"timeis:"+time); Thread.sleep(time); returnno; } }; returntask; } }
运行结果为最先结束的线程结果先被处理:
thead:0timeis:4200 thead:1timeis:6900 thead:2timeis:2900 thead:3timeis:9000 thead:4timeis:7100 0143CompletionServiceallis:10
总结
以上就是本文关于Java利用future及时获取线程运行结果的全部内容,希望对大家有所帮助。感兴趣的朋友可以参阅:Java多线程ForkJoinPool实例详解、Java通过卖票理解多线程、Java多线程之readwritelock读写分离的实现代码等,有什么问题可以随时留言,欢迎大家交流讨论。