NO.10 Callable与Future的应用
代码:
package thread; import java.util.Random; 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.Future; public class CallableAndFature { /** * @param args * @throws ExecutionException * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException, ExecutionException { /** * code 1 */ ExecutorService pool = Executors.newSingleThreadExecutor(); Future<String> future = pool.submit(new Callable<String>() { @Override public String call() throws Exception { Thread.sleep(2000); return "hello"; } }); System.out.println(future.get()); pool.shutdown(); /** * code 2 */ ExecutorService pool2 = Executors.newFixedThreadPool(5); CompletionService<Integer> server = new ExecutorCompletionService<Integer>(pool2); for(int i = 1; i <= 10; i ++) { final int seq = i; server.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { Thread.sleep(new Random().nextInt(5000)); return seq; } }); } for(int i = 1; i <= 10; i ++) { System.out.println(server.take().get()); } } }