标签:next ring callable 移除 interrupt block except string ret
1 import java.util.Random; 2 import java.util.concurrent.Callable; 3 import java.util.concurrent.CompletionService; 4 import java.util.concurrent.ExecutionException; 5 import java.util.concurrent.ExecutorCompletionService; 6 import java.util.concurrent.ExecutorService; 7 import java.util.concurrent.Executors; 8 9 public class CallableAndFuture { 10 11 public static void main(String[] args) { 12 ExecutorService threadPool = Executors. newFixedThreadPool(10); 13 CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool); 14 15 for (int i = 0; i < 10; i++) { 16 final int seq = i; 17 System. out.println("开始提交第" + seq + "个任务"); 18 completionService.submit( new Callable<Integer>() { 19 20 @Override 21 public Integer call() throws Exception { 22 Thread. sleep(new Random().nextInt(5000)); 23 return seq; 24 } 25 }); 26 } 27 28 for (int i = 0; i < 10; i++) { 29 try { 30 // 取出并移除表示下一个已完成任务的 Future,如果目前不存在这样的任务,则等待。 31 Integer seq = completionService.take().get(); 32 System. out.println("第" + seq + "个任务返回"); 33 } catch (InterruptedException e) { 34 e.printStackTrace(); 35 } catch (ExecutionException e) { 36 e.printStackTrace(); 37 } 38 } 39 } 40 41 }
使用CompletionService结合ExecutorService批处理任务
标签:next ring callable 移除 interrupt block except string ret
原文地址:http://www.cnblogs.com/zhangyuhang3/p/6872674.html