标签:latch 16px read lease rac style cat redo err
CountDownLatch
public class CountDownLatchDemo { //原理: //countDownLatch.countDown(); // 数量-1 //countDownLatch.await(); // 等待计数器归零,然后再向下执行 //每次有线程调用 countDown() 数量-1,假设计数器变为0,countDownLatch.await() 就会被唤醒,继续 执行! public static void main(String[] args) throws InterruptedException { //总数是6,必须要执行任务的时候,再使用 CountDownLatch count = new CountDownLatch(6); for (int i = 0; i <=6; i++) { new Thread(()->{ System.out.println(Thread.currentThread().getName()+"Go out"); count.countDown();//数量减一 },String.valueOf(i)).start(); } count.await();//等待计数器归0,然后再向下执行 System.out.println("Close Door"); // count.countDown(); } }
CyclicBarrier
1 public class CyclicBarrierDemo { 2 public static void main(String[] args) { 3 //如果设置的数比循环里面的数大,循环里面的不满足就会卡在barrier.await();等待这里 4 CyclicBarrier barrier = new CyclicBarrier(9,()->{ 5 System.out.println("召唤神龙耶"); 6 }); 7 8 9 for (int i = 0; i <=7; i++) { 10 int temp = i; 11 //lambda能操作 i 吗 12 new Thread(()->{ 13 System.out.println(Thread.currentThread().getName()+"收集"+temp+"个龙珠"); 14 try { 15 barrier.await(); 16 } catch (InterruptedException e) { 17 e.printStackTrace(); 18 } catch (BrokenBarrierException e) { 19 e.printStackTrace(); 20 } 21 }).start(); 22 } 23 } 24 }
Semaphore
1 public class SemahoreDome { 2 public static void main(String[] args) { 3 //线程数量,停车位 限流会用到 4 5 Semaphore semaphore = new Semaphore(3); 6 7 for (int i = 0; i <=6; i++) { 8 new Thread(()->{ 9 //acquire()得到 10 try { 11 semaphore.acquire(); 12 System.out.println(Thread.currentThread().getName()+"得到 车位"); 13 TimeUnit.SECONDS.sleep(2); 14 System.out.println(Thread.currentThread().getName()+"离开停车场"); 15 } catch (InterruptedException e) { 16 e.printStackTrace(); 17 }finally { 18 semaphore.release();//release() 释放 19 } 20 },String.valueOf(i)).start(); 21 } 22 23 } 24 }
标签:latch 16px read lease rac style cat redo err
原文地址:https://www.cnblogs.com/rzkwz/p/12696947.html