java开启多个线程,执行完成后再执行主线程

代码例子:

   public static void main(String[] args) throws Exception{
        int count = 10;
        List<Thread> workers = new ArrayList<>();
        for(int i = 0; i < count; i++) {
            final int s = i;
            Thread worker = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(500);
                        System.out.println("执行子线程" + s);
                    }catch (Exception e){

                    }
                }
            });
            worker.start();
            workers.add(worker);
        }
        for(int i = 0; i < count; i++) {
            workers.get(i).join();
        }
        System.out.println("执行主线程");
    }

结果:

执行子线程7
执行子线程6
执行子线程3
执行子线程2
执行子线程9
执行子线程8
执行子线程5
执行子线程4
执行子线程1
执行子线程0
执行主线程

查看jdk中join源码,你会发现,官方翻译是等待线程死亡,也就是线程执行结束

/**
     * Waits for this thread to die.
     *
     * <p> An invocation of this method behaves in exactly the same
     * way as the invocation
     *
     * <blockquote>
     * {@linkplain #join(long) join}{@code (0)}
     * </blockquote>
     *
     * @throws  InterruptedException
     *          if any thread has interrupted the current thread. The
     *          <i>interrupted status</i> of the current thread is
     *          cleared when this exception is thrown.
     */
    public final void join() throws InterruptedException {
        join(0);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值