Java等线程池执行完所有任务后再执行主线程
生活随笔
收集整理的這篇文章主要介紹了
Java等线程池执行完所有任务后再执行主线程
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
因為要定時往數據庫插入上百萬數據,插入完之后再修改另外一部分數據, 怎么在線程池執行完所有任務后再執行主線程呢
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();}} }轉載于:https://my.oschina.net/u/2462659/blog/1541693
總結
以上是生活随笔為你收集整理的Java等线程池执行完所有任务后再执行主线程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: swift_通知的使用
- 下一篇: java美元兑换,(Java实现) 美元