java线程中的异步和同步,并不是走路,一定要搞清楚。那么join方法嘛,就是异步变同步。线程阻塞,就再楼下一直等着它想要的状态出现喽。直接上代码,先来看Future获取线程执行结果的使用示例:
public class TestCallable { public static void main(String[] args) throws Exception { ExecutorService executorService = Executors.newCachedThreadPool(); Task task = new Task(); Future<Integer> future = executorService.submit(task); executorService.shutdown(); Thread.sleep(3000); System.out.println("主线程" + Thread.currentThread().getName() + "正在执行任务"); System.err.println("任务运行结果:" + future.get()); System.out.println("所有任务执行完毕"); } } class Task implements Callable<Integer> { @Override public Integer call() throws InterruptedException { System.out.println("子线程" + Thread.currentThread().getName() + "在进行计算:"); Thread.sleep(4 * 1000); int sum = 0; for (int i = 0; i < 100; i++) { sum += i; } return sum; } }
同样的,FutureTask。http://www.cnblogs.com/dolphin0520/p/3949310.html