CompletionService的poll方法
1、poll():马上返回完成的任务,若没有,则返回null
2、poll(long timeout, TimeUnit unit): 等待timeout时间,如果大于最短任务完成时间,则获取任务结果返回,结束等待;如果小于任务完成时间,则等待任务完成,获取结果并返回
实验代码:
import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class MyPoll { public static void main(String[] args) { // TODO 自动生成的方法存根 ExecutorService executor=Executors.newCachedThreadPool(); CompletionService<String> comservice=new ExecutorCompletionService<String>(executor); MyPollCallble callable=new MyPollCallble(); MyPollCallble_time time_cable=new MyPollCallble_time(); comservice.submit(callable); comservice.submit(time_cable); //poll():获取并移除表示下一个已完成任务的future。如果不存完成的任务,则返回null,即不会出现阻塞效果 // System.out.println(comservice.poll()); try { //等待指定timeout时间,在timeout之内获得值即向下执行,如果超时也向下执行 System.out.println("get1 at"+System.currentTimeMillis()); System.out.println("1 "+comservice.poll(1000, TimeUnit.SECONDS).get()); System.out.println("get2 at"+System.currentTimeMillis()); System.out.println("2 "+comservice.poll(2000, TimeUnit.SECONDS).get()); System.out.println("get3 at"+System.currentTimeMillis()); } catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } catch (ExecutionException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } } class MyPollCallble implements Callable<String>{ @Override public String call() throws Exception { // TODO 自动生成的方法存根 System.out.println("start"); System.out.println("first "+System.currentTimeMillis()); Thread.sleep(2000); System.out.println("end "+System.currentTimeMillis()); return "finish"; } } class MyPollCallble_time implements Callable<String>{ @Override public String call() throws Exception { // TODO 自动生成的方法存根 System.out.println("start time"); System.out.println("second "+System.currentTimeMillis()); Thread.sleep(3000); System.out.println("end time "+System.currentTimeMillis()); return "finish time"; } }
实验结果:
start first 1492676279057 get1 at1492676279057 start time second 1492676279057 end 1492676281061 1 finish get2 at1492676281061 end time 1492676282064 2 finish time get3 at1492676282064
可以看到get1与get2之间相差2秒,表明是在等待任务完成,而不是未获得值继续向下执行