1. join
thread的join方法使当前线程等待thread线程执行结束:
@Test
public void test1() throws InterruptedException {
Thread t1 = new Thread(() -> log.debug("test1"), "t1");
t1.start();
t1.join(); // 当前主线程等待t1线程执行结束
log.debug("测试结束");
}
执行结果为:
09:15:34.243 com.ruizhe.springcloud.ConcurrentTest [t1] - test1
09:15:34.243 com.ruizhe.springcloud.ConcurrentTest [main] - 测试结束
2. 使用FutureTask
FutrueTask实现了Runnable和Future接口。Future代表了一个异步计算的结果,可以通过get方法阻塞当前线程获取执行结果:
@Test
public void test2() throws InterruptedException, ExecutionException {
// 接受一个Runnalbe接口创建一个Futrue任务
FutureTask<String> task = new FutureTask<>(() -> {
log.debug("执行t1");
return "test2";
});
Thread t1 = new Thread(task, "t1");
t1.start();
log.debug("t1的返回结果为:{}", task.get());
log.debug("测试结束");
}
执行结果:
09:17:00.030 com.ruizhe.springcloud.ConcurrentTest [t1] - 执行t1
09:17:00.030 com.ruizhe.springcloud.ConcurrentTest [main] - t1的返回结果为:test2
09:17:00.030 com.ruizhe.springcloud.ConcurrentTest [main] - 测试结束