标签:
ExecutorService 创建线程池,线程池可以定义线程的数量
future指线程执行后需要返回的结果,结果可以自己定义
callable相当于runnable
package com.condition; 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; import java.util.concurrent.TimeUnit; public class CallableAndFuture { /** * @param args */ public static void main(String[] args) { ExecutorService threadPool = Executors.newSingleThreadExecutor(); Future<String> future = threadPool.submit( new Callable<String>() { public String call() throws Exception { Thread.sleep(2000); return "hello"; }; } ); System.out.println("等待结果"); try { System.out.println("拿到结果:" + future.get()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
标签:
原文地址:http://www.cnblogs.com/hzmbbbb/p/4280283.html