Java等線程池執行完全部任務後再執行主線程

由於要定時往數據庫插入上百萬數據,插入完以後再修改另一部分數據, 怎麼在線程池執行完全部任務後再執行主線程呢java

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


public class Test {



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

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

    public static void main(String[] args) {
        new Test().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(time);
            } catch (InterruptedException e) {
            }
            System.out.println(Thread.currentThread().getName() + "執行完了,耗時:" + time / 1000 + "秒");
            cdl.countDown();
        }
    }
}
相關文章
相關標籤/搜索