JAVA线程池中的Callable和Future
import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * Callable Future completionService test * * Future取得结果类型和Callable返回的结果 * * Callable需要ExecutorService使用submit方式提交 * * CompletionService 用于提交一组Callable,其中take方法返回已经完成的Callable任务 * * @author duwenlei * */ public class CallableFutureTest { private static void testCallable() throws Exception { ExecutorService service = Executors.newSingleThreadExecutor(); Future<String> future = service.submit(new Callable<String>() { @Override public String call() throws Exception { Thread.sleep(5000); //停止5秒返回 return "hello"; } }); System.out.println("等待结果"); System.out.println("取得结果:"+future.get()); //System.out.println("取得结果:"+future.get(1, TimeUnit.SECONDS)); service.shutdown(); } private static void testCompletionService() throws Exception{ ExecutorService executor = Executors.newFixedThreadPool(3); CompletionService<Integer> service = new ExecutorCompletionService<Integer>(executor); //需要一个线程池 for (int i = 1; i <= 10; i++) { final int seq = i; service.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(service.take().get()); } executor.shutdown(); } public static void main(String[] args) { try { testCallable(); } catch (Exception e) { e.printStackTrace(); } try { testCompletionService(); } catch (Exception e) { e.printStackTrace(); } } }
如果有使用请标明来源:http://www.cnblogs.com/duwenlei/