并发编程之二:等待线程运行结束

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] - 测试结束

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值