Java--JUC--Lock之Condition(精确的通知访问)

  1.  

    synchronized:wait和notify

  2. lock:await和signal 

  3. notify唤醒所有等待的线程,这些线程疯抢,谁抢到是谁的
  4. signal能够精确的唤醒某个线程
  5. 实际系统之间系统调度举例:
    1. package com.model.concurrent;
      
      import java.util.concurrent.locks.Condition;
      import java.util.concurrent.locks.Lock;
      import java.util.concurrent.locks.ReentrantLock;
      
      /**
       * 备注:多线程之间循序调用,实现A->B->C
       * 三个线程,要求如下:
       * A打印五次,B打印十次,C打印十五次
       * 接着
       * A打印五次,B打印十次,C打印十五次
       * 来十轮
       *
       *
       * */
      class Print{
      
          private int num=1;
          private Lock lock=new ReentrantLock();
          private Condition c1=lock.newCondition();
          private Condition c2=lock.newCondition();
          private Condition c3=lock.newCondition();
      
          public void print_a(){
              lock.lock();
              try {
              if (num!=1){
                  c1.await();
              }
              for (int i=0;i<5;i++) {
                  System.out.println("A\t"+i);
              }
              num++;
              c2.signal();
              }catch (Exception e){
                  e.printStackTrace();
              }finally {
                  lock.unlock();
              }
          }
          public void print_b(){
              lock.lock();
              try {
              if (num!=2){
                  c2.await();
              }
              for (int i=0;i<10;i++) {
                  System.out.println("B\t"+i);
              }
              num++;
              c3.signal();
              }catch (Exception e){
                  e.printStackTrace();
              }finally {
                  lock.unlock();
              }
          }
          public void print_c(){
              lock.lock();
              try {
              if (num!=3){
                  c3.await();
              }
              for (int i=0;i<15;i++) {
                  System.out.println("C\t"+i);
              }
              num=1;
              c1.signal();
              }catch (Exception e){
                  e.printStackTrace();
              }finally {
                  lock.unlock();
              }
          }
      }
      public class ConditionDemo {
          public static void main(String[] args) {
              Print print=new Print();
              new Thread(() ->{
                  for (int i = 0; i < 10; i++) {
                      print.print_a();
                  }
              },"A").start();
      
              new Thread(() ->{
                  for (int i = 0; i < 10; i++) {
                      print.print_b();
                  }
              },"B").start();
              new Thread(() ->{
                  for (int i = 0; i < 10; i++) {
                      print.print_c();
                  }
              },"C").start();
          }
      }

       

          
posted @ 2021-06-04 21:16  张紫韩  阅读(43)  评论(0编辑  收藏  举报