判断线程结束
判斷線程結束
使用ExecutorService.isTerminated方式
public void executor() throws InterruptedException{ExecutorService executorService = Executors.newFixedThreadPool(threadNum);List<Callable<Object>> calls = new ArrayList<>();for (int i = 0; i < threadNum; i++) {int flag = 0 ;while (flag < 10000) {calls.add(new Callable<Object>() {@Overridepublic Object call() throws Exception {int aaa = new Random().nextInt(100);System.out.println(aaa);return aaa;}});flag ++ ;}}executorService.invokeAll(calls);executorService.shutdown();while (true) {if(executorService.isTerminated()){System.out.println("線程已經(jīng)全部結束");break;}else{System.out.println("線程未全部結束");}Thread.sleep(1000);}System.exit(-1);}shutdown
void shutdown() 啟動一次順序關閉,執(zhí)行以前提交的任務,但不接受新任務。若已經(jīng)關閉,則調用沒有其他作用。
isTerminated
boolean isTerminated() 若關閉后所有任務都已完成,則返回true。注意除非首先調用shutdown或shutdownNow,否則isTerminated永不為true。返回:若關閉后所有任務都已完成,則返回true。
使用CountDownLatch
public void start() { System.out.println("開始開始開始開始開始開始");final CountDownLatch countDownLatch = new CountDownLatch(threadNum);ExecutorService executor = Executors.newFixedThreadPool(threadNum);for (int i = 0; i < threadNum; i++) {executor.execute(new Runnable() {@Overridepublic void run() {int j= 3000;while (true) {j--;System.out.println(j);if (j == 0) {System.out.println("結束一個");countDownLatch.countDown();break;}}}});}try {countDownLatch.await();} catch (InterruptedException e) {e.printStackTrace();}System.out.println("結束結束結束結束結束結束結束");System.exit(-1);}countDown
public void countDown()
遞減鎖存器的計數(shù),如果計數(shù)到達零,則釋放所有等待的線程。
如果當前計數(shù)大于零,則將計數(shù)減少。如果新的計數(shù)為零,出于線程調度目的,將重新啟用所有的等待線程。
如果當前計數(shù)等于零,則不發(fā)生任何操作。
await
public void await() throws InterruptedException
使當前線程在鎖存器倒計數(shù)至零之前一直等待,除非線程被 中斷。
轉載于:https://www.cnblogs.com/cuiyf/p/7651282.html
總結
- 上一篇: 结构体内存对齐(如何计算结构体的大小)
- 下一篇: 17-9--18:了解Linux的命令格