Wait for the wake-up mechanism: communication between threads (producer and consumer cases)

1.1 Communication between threads

**Concept:** Multiple threads are processing the same resource, but the thread tasks are different

For example: Mr. Araki produces small bread, and Dio comes to eat bread. This bread is the same resource.

However, one is to produce and the other is to eat, so there is a thread communication problem between Mr. Araki and Dio.

When multiple threads execute concurrently, our CPU performs high-speed switching and then switches threads. But when we have to do multiple threads to complete the same task, then some coordination and communication between multiple threads are needed. This is why we have to deal with communication between threads.

Moreover, when multiple threads are operating on the same data, in order to avoid contention for the same shared variable, (self-understanding: Mr. Araki will eat it when Mr. Araki does not produce a bun).

Through a certain method, each thread can effectively use resources. This method is called waiting to wake up mechanism .

1.2 Waiting for wake-up mechanism

Insert picture description here

Because we don’t want to change the bread anymore, let’s let Dio eat buns

//包子属性
class BaoZi{
    
    
    /*
  * 有皮
  * 有馅
  * 对包子状态的判断
  * */
    String xian;
      String pi;
      boolean flag=false;
 }

//消费者
class Consumer implements Runnable{
    
    
    private  BaoZi baoZi;
    private  Lock lock;   //锁对象
    public Consumer(BaoZi baoZi, Lock lock) {
    
    
        this.baoZi = baoZi;
        this.lock = lock;
    }
    @Override
    public void run() {
    
    
       while (true){
    
    
           synchronized (lock){
    
    
               //判断有没有包子 (没有包子)
               if (baoZi.flag==false){
    
    
                   try {
    
    
                       lock.wait();
                   } catch (InterruptedException e) {
    
    
                       e.printStackTrace();
                   }
               }
               System.out.println("开始吃"+this.baoZi.pi+this.baoZi.xian+"的包子");
               //吃完包子后修改状态
               baoZi.flag=false;
               //吃完唤醒包子铺线程,生产包子 (饿了 ,来唤醒生产者)
               lock.notify();
               System.out.println("吃完了"+this.baoZi.pi+this.baoZi.xian+"的包子");
               System.out.println("============================================");
           }
       }
    }
}

//生产者
 class  Producer  implements Runnable{
    
    
    private  BaoZi baoZi;
    private  Lock lock;
public Producer (BaoZi baoZi, Lock lock) {
    
    
    this.baoZi = baoZi;
    this.lock = lock;
}
@Override
public void run() {
    
    
    int count=0;
    //让包子铺一直做包子
    while (true){
    
    
        synchronized (lock){
    
    
            //首先判断有没有包子    (一开始没有包子)
            if (baoZi.flag){
    
    
                try {
    
    
                    lock.wait();  //等待
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
            }
            // wait之后的代码被消费者唤醒后执行,包子铺生产包子
            if (count%2==0){
    
    
                baoZi.pi="薄皮";
                baoZi.xian="牛肉大葱";
            }else {
    
    
                baoZi.pi="冰皮";
                baoZi.xian="韭菜鸡蛋";
            }
            count++;
            System.out.println("正在做"+baoZi.pi+baoZi.xian+"馅的包子");
            //包子正在做
            try {
    
    
                System.out.println("做包子中························");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
            this.baoZi.flag=true;
            //唤醒吃包子的消费者
            lock.notify();
            System.out.println("做好了"+baoZi.pi+baoZi.xian+"馅的包子");
        }
    }
}
}
//主方法
public class P_CThreadTest {
    
    
    public static void main(String[] args) {
    
    
        BaoZi baoZi = new BaoZi();
        Lock lock = new ReentrantLock();
        new Thread(new Producer(baoZi,lock)).start();
        new Thread(new Consumer(baoZi,lock)).start();
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/agood_man/article/details/108246693