线程池如何保证所有子线程运行完再执行主线程

package pub.qingyun.weixin;

/**
 * @Author CQY
 * @Date 2020/7/13/013 19:28
 * @Version 1.0
 **/

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test1 {

    public static ExecutorService executorService = Executors.newFixedThreadPool(10);
    private static CountDownLatch cdl = new CountDownLatch(100);
    private static final Random random = new Random();

    public void test() {
        for (int i = 0; i < 100; i++) {
            executorService.execute(new ThreadTest());
        }
    }

    public static void main(String[] args) {
        new Test1().test();

        //插入数据完成后  执行修改操作
        try {
            cdl.await();
        } catch (InterruptedException e) {
        }
        System.out.println("它们已经插完啦..............................");
        executorService.shutdown();

    }

    class ThreadTest implements Runnable {

        public void run() {
            //执行插入数据操作  每次插入一条
            // 模拟耗时
            int time = random.nextInt(10000);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
            System.out.println(Thread.currentThread().getName() + "执行完了,耗时:" + time / 1000 + "秒");
            cdl.countDown();
            System.out.println("Count:" + cdl.getCount());
        }
    }
}
package pub.qingyun.weixin;

import java.util.Vector;

/**
 * @author Zhang, Tianyou
 * @version 2014年11月21日 下午11:15:27
 */

public class ThreadSubMain2 {

    public static void main(String[] args) {
        // 使用线程安全的Vector
        Vector<Thread> threads = new Vector<Thread>();
        for (int i = 0; i < 10; i++) {

            Thread iThread = new Thread(() -> {

                try {
                    Thread.sleep(1000);
                    // 模拟子线程任务
                } catch (InterruptedException e) {
                }
                System.out.println("子线程" + Thread.currentThread() + "执行完毕");

            });
            threads.add(iThread);
            iThread.start();
        }

        for (Thread iThread : threads) {
            try {
                // 等待所有线程执行完毕
                iThread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("主线执行。");
    }

}

package pub.qingyun.weixin;

import java.util.concurrent.*;


/**
 * @Author CQY
 * @Date 2020/7/13/013 21:05
 * @Version 1.0
 **/
public class CompletionServiceTest {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        CompletionService<String> completionService = new ExecutorCompletionService<>(executorService);
        for (int i = 0; i < 20; i++) {
            completionService.submit(new ReturnAfterSleepCallable(i));
        }
        System.out.println("after submit");
        for (int i = 0; i < 20; i++) {
            System.out.println("result: " + completionService.take().get()); // 这个方法是阻塞的
        }
        System.out.println("after get");
        executorService.shutdown();
    }

}

class ReturnAfterSleepCallable implements Callable<String> {
    int sleep;

    public ReturnAfterSleepCallable(int sleep) {
        this.sleep = sleep;
    }

    @Override
    public String call() throws Exception {
        System.out.println("-----------------------------");
        TimeUnit.SECONDS.sleep(1);
        return System.currentTimeMillis() + ",sleep=" + String.valueOf(sleep);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值