import java.util.concurrent.*; public class TaskCallable implements Callable{ @Override public Integer call() throws Exception { System.out.println("异步线程【" + Thread.currentThread().getName() + "】,计算中..."); Thread.sleep(3000); return 2; } public static void main(String args[]) throws ExecutionException, InterruptedException { ExecutorService executor = Executors.newCachedThreadPool(); TaskCallable task = new TaskCallable(); Future result = executor.submit(task); System.out.println("主线程【" + Thread.currentThread().getName() + "】,等待结果..."); System.out.println("主线程【" + Thread.currentThread().getName() + "】,异步线程" + result.get()); executor.shutdown(); } }
结果:
主线程【main】,等待结果... 异步线程【pool-1-thread-1】,计算中... 主线程【main】,异步线程2



