タスクを終了するにはいくつかの方法を待ってマルチスレッド

たとえば、メインスレッドは、n個のタスクを提出する、スレッド・プールを作成するには、メインスレッドがタスクの全て終了した後に他のことをやっていきたいと思います。


1、方法awaitTerminationを使用

public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(3); int i = 0; AtomicInteger result = new AtomicInteger(0); while (i < 10) { i++; executor.execute(() -> { //每执行一次,对result加1 System.out.println(result.addAndGet(1)); }); } System.out.println("调用shutdown()方法时,result的值为:" + result.get()); executor.shutdown(); try { //等待所有任务结束,最多等待30分钟 executor.awaitTermination(30, TimeUnit.MINUTES); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("计算完成,result的值为:" + result.get() + ",可以继续处理其他事情了"); } 

ブールawaitTermination(長いタイムアウト、TimeUnitでユニット)的作用:

シャットダウン要求後にすべてのタスクが実行を完了した、まで、
またはタイムアウトが発生する、または現在のスレッドは中断され、
いずれか早い方。


2、ツールを使ってたCountDownLatch

public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(3); CountDownLatch latch = new CountDownLatch(10); AtomicInteger result = new AtomicInteger(0); for (int i = 1; i <= 10; i++) { executor.execute(() -> { //do something... System.out.println(result.addAndGet(1)); //then latch.countDown(); }); } System.out.println("调用shutdown()方法时,result的值为:" + result.get()); executor.shutdown(); try { latch.await();//等待任务结束:其实是等待latch值为0 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("计算完成,result的值为:" + result.get() + ",可以继续处理其他事情了"); } 

たCountDownLatchは、作成時にサイズを指定する必要がありますし、再初期化することができないので、タスクの数を知るに適用。

// TODO:たCountDownLatchかどうかの並べ替えの指示を禁止しますか?(ビューの公式の観点から、例えば、それは!勉強になります)

public void example() { CountDownLatch doneSignal = new CountDownLatch(10); Executor e = Executors.newFixedThreadPool(10); for (int i = 0; i < 10; ++i) // create and start threads e.execute(new WorkerRunnable(doneSignal, i)); try { doneSignal.await(); // wait for all to finis } catch (InterruptedException e1) { e1.printStackTrace(); } } class WorkerRunnable implements Runnable { private final CountDownLatch doneSignal; private final int i; WorkerRunnable(CountDownLatch doneSignal, int i) { this.doneSignal = doneSignal; this.i = i; } public void run() { doWork(i); doneSignal.countDown(); } void doWork(int i) { } } 

他の

// TODO



著者:maxwellyue
リンクします。https://www.jianshu.com/p/bcbfb58d0da5
出典:ジェーン・ブック
著者によって予約ジェーンブックの著作権は、いかなる形で再現され、承認を得るために、作者に連絡して、ソースを明記してください。

おすすめ

転載: www.cnblogs.com/xiaoshen666/p/11258556.html