Java并发:CountDownLatch、CyclicBarrier和 Semaphore
CountDownLatch Demo
所有线程离开后,主线程才能离开
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| package com.cdinit;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo { public static void main(String[] arg) throws Exception{ testLeave(); }
// 所有线程离开后,主线程才能离开 public static void testLeave() throws Exception{ CountDownLatch countDownLatch = new CountDownLatch(6); for (int i=1;i<=6;i++){ new Thread(()->{ System.out.println(Thread.currentThread().getName() + " 离开..."); countDownLatch.countDown(); },String.valueOf(i)).start(); } countDownLatch.await(); System.out.println(Thread.currentThread().getName() +"主线程离开..."); } }
|
CyclicBarrier Demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| package com.cdinit;
import java.util.concurrent.CyclicBarrier;
// 集齐七颗龙珠,召唤神龙 public class CyclicBarrierDemo {
private static final int NUMBER = 7;
public static void main(String[] ag) throws Exception{ CyclicBarrier cyclicBarrier = new CyclicBarrier(NUMBER,()->{ System.out.println("召唤神龙..."); });
for(int i=1;i<=7;i++){ int tempInt = i; new Thread(()->{ try { System.out.println(Thread.currentThread().getName() + "收集了" + tempInt + "龙珠..."); cyclicBarrier.await(); } catch (Exception e) { e.printStackTrace(); } },String.valueOf(i)).start(); }
} }
|
Semaphore Demo
抢车位
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| package com.cdinit;
import java.util.Random; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit;
public class SemaphoreDemo { public static void main(String[] arg) throws Exception{ Semaphore semaphore = new Semaphore(3); // 3个停车位 for(int i=1;i<=6;i++){ // 模拟6个汽车 new Thread(()->{ try { semaphore.acquire(); System.out.println(Thread.currentThread().getName() + "号抢到车位..."); TimeUnit.SECONDS.sleep(new Random().nextInt(8)); System.out.println(Thread.currentThread().getName() + "号Leave离开车位..."); } catch (Exception e) { e.printStackTrace(); } finally { semaphore.release(); } },String.valueOf(i)).start(); } } }
|
参考
Java并发编程:CountDownLatch、CyclicBarrier和 Semaphore