获取子线程返回结果(Future的使用)

当我们在主线程中起一个线程去处理任务,通常这个处理过程是异步的,主线程直接响应结果。
但如果这个过程是同步的,即主线程等待子线程的响应后,再去响应,应该怎么做?

执行任务的类,类似实现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...");
	}
}

猜你喜欢

转载自516100981.iteye.com/blog/2399490