java如何在多執行緒執行完成後再執行某個方法
阿新 • • 發佈:2019-01-03
package com.whj.feign.client; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; public class Test1 { public static void main(String[] args) throws InterruptedException { final int threadCount = 10; final AtomicInteger count = new AtomicInteger(threadCount); final Object waitObject = new Object(); ExecutorService pool = Executors.newCachedThreadPool(); for (int i = 0; i < threadCount; i++) { final int j = i; pool.execute(new Runnable() { @Override public void run() { System.out.println("執行執行緒號:" + j); synchronized (waitObject) { int cnt = count.decrementAndGet(); if (cnt == 0) { waitObject.notifyAll(); } } } }); } synchronized (waitObject) { while (count.get() != 0) { waitObject.wait(); } } Thread.sleep(1000); System.out.println("結束執行緒"); System.exit(0); }
執行結果