Multithreading wait several ways to end the task

For example, the main thread to create a thread pool, to submit n tasks, want the main thread to continue to do other things after all the end of the task.


1, using the method 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() + ",可以继续处理其他事情了"); } 

boolean awaitTermination(long timeout, TimeUnit unit)的作用:

Blocks until all tasks have completed execution after a shutdown request,
or the timeout occurs, or the current thread is interrupted,
whichever happens first.


2, with the tools 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() + ",可以继续处理其他事情了"); } 

Applicable to know the number of tasks, because CountDownLatch must specify the size when you create and can not be re-initialized.

// TODO: CountDownLatch whether prohibit instruction reordering? (Examples from the official point of view, it will! Be studied)

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) { } } 

other

//ALL



Author: maxwellyue
link: https: //www.jianshu.com/p/bcbfb58d0da5
Source: Jane book
Jane book copyright reserved by the authors, are reproduced in any form, please contact the author to obtain authorization and indicate the source.

Guess you like

Origin www.cnblogs.com/xiaoshen666/p/11258556.html