但如果这个过程是同步的,即主线程等待子线程的响应后,再去响应,应该怎么做?
执行任务的类,类似实现Runnable。
要设置一个泛型,即任务的返回结果
public class MyCallable implements Callable<Integer> { //返回一个随机数 @Override public Integer call() throws Exception { int result=new Random().nextInt(20); System.out.println(Thread.currentThread().getName()+"计算中..."); //模拟耗时 Thread.sleep(2000); return result; } }
主线程
public class Main { public static void main(String[] args) { //设置一个future返回结果 FutureTask<Integer> future=new FutureTask<>(new MyCallable()); //启动线程开始执行任务 new Thread(future).start(); System.out.println("before future get..."); try { //如果任务没有完成 主线程会阻塞在这里 直到有返回结果 System.out.println(future.get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } System.out.println("after future..."); } }