标签:style io ar 使用 java for sp div on
import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class FutureDemo { public static void main(String[] args) throws Exception, ExecutionException { ExecutorService threadPool = Executors.newFixedThreadPool(3); Future<String> future = threadPool.submit(new Callable<String>() { @Override public String call() throws Exception { Thread.sleep(10000); return "hello"; } }); System.out.println("等待结果"); System.out.println("结果是:"+future.get()); } }我们知道ExecutorService中执行任务的方法有一个是execute()但是它没有返回值,而subimt()方法有返回值是Future,Future有一个get方法,它是返回真正的结果。
public class FutureDemo { public static void main(String[] args) throws Exception, ExecutionException { ExecutorService threadPool = Executors.newFixedThreadPool(3); ExecutorCompletionService<Integer> ecs = new ExecutorCompletionService<Integer>(threadPool); for(int i=0;i<10;i++){ final int seq = i; ecs.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { Thread.sleep(new Random().nextInt(5000)); return seq; } }); } System.out.println("结果-----------"); for(int i=0;i<10;i++){ Future<Integer> take = ecs.take(); System.out.println("获取结果是:"+take.get()); } } }
结果----------- 获取结果是:0 获取结果是:3 获取结果是:2 获取结果是:5 获取结果是:6 获取结果是:1 获取结果是:4 获取结果是:7 获取结果是:8 获取结果是:9
标签:style io ar 使用 java for sp div on
原文地址:http://blog.csdn.net/coderinchina/article/details/40624507