判断线程结束
判断线程结束
-
使用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>() { @Override public 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("线程已经全部结束"); break; }else{ System.out.println("线程未全部结束"); } Thread.sleep(1000); } System.exit(-1); }
shutdown
void shutdown() 启动一次顺序关闭,执行以前提交的任务,但不接受新任务。若已经关闭,则调用没有其他作用。
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() { @Override public 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()
递减锁存器的计数,如果计数到达零,则释放所有等待的线程。
如果当前计数大于零,则将计数减少。如果新的计数为零,出于线程调度目的,将重新启用所有的等待线程。如果当前计数等于零,则不发生任何操作。
await
public void await() throws InterruptedException
使当前线程在锁存器倒计数至零之前一直等待,除非线程被 中断。