5個執行緒先列印Hello再列印world
問題
5個執行緒列印Hello 和world :要求5個執行緒先連續列印全部Hello ,再連續列印全部world 。
實現
題目中指明5個執行緒合作,就可以先讓5個執行緒列印Hello 。執行緒列印完畢後就在CyclicBarrier 例項上等待,直到CyclicBarrier 累計執行緒數到達指定值,所有執行緒都會同時放行。放行後的執行緒繼續列印world 即可完成要求。
public class CyclicBarrierAnswer { // 同時用於定義CyclicBarrier和執行緒池的值 private static final int THREADS_COUNT = 5; public static void main(String[] args) { // CyclicBarrier例項,已設定等待執行緒數 CyclicBarrier barrier = new CyclicBarrier(THREADS_COUNT, System.out::println); ExecutorService service = Executors.newFixedThreadPool(THREADS_COUNT); for (int i = 0; i < THREADS_COUNT; i++) { // 執行緒池執行邏輯 service.execute(() -> { try { System.out.println(Thread.currentThread().getName() + ": Hello"); // 執行緒列印上述內容後都在這裡等待 barrier.await(); // 累計達目標執行緒數,放行所有執行緒 System.out.println(Thread.currentThread().getName() + ": world"); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } }); } } }
執行結果
pool-1-thread-2: Hello pool-1-thread-3: Hello pool-1-thread-4: Hello pool-1-thread-5: Hello pool-1-thread-1: Hello pool-1-thread-1: world pool-1-thread-4: world pool-1-thread-5: world pool-1-thread-3: world pool-1-thread-2: world