线程通讯之消费者和生产者传统版

2022-05-13 12:28:07 浏览数 (1)

一般由Synochized和lock两种设计传统生产者消费的方法

Synochized和Lock的区别各自的优缺点

lock更加牛逼一点所以一班我们用lock,其实设计方法

话不多说,直接code

代码语言:javascript复制
package jucTest;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


class zi{
    volatile int num=0;
    Lock lock=new ReentrantLock();
    Condition condition=lock.newCondition();

     public void addNum(){
         lock.lock();
         try {
             while (num!=0)
             { condition.await();//线程进入等待
             }
             num  ;
             System.out.println(Thread.currentThread().getName() "操作后num为" num);
             condition.signalAll();//唤醒所有被挂起的线程
         } catch (InterruptedException e) {
             e.printStackTrace();
         }finally {
             lock.unlock();
         }

     }

    public void derNum(){
        lock.lock();
        try {
            while (num==0)
            {
            condition.await();//线程进入等待
            }
        num--;
        System.out.println(Thread.currentThread().getName() "操作后num为" num);
        condition.signalAll();//唤醒所有被挂起的线程
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
        lock.unlock();
        }
    }
}
public class LockBuildAndRest {
    public static void main(String[] args){
        zi zi=new zi();
        for(int i=0;i<5;i  ){
            new Thread(()->{
              zi.addNum();
            },"AA").start();
        }

        for(int i=0;i<5;i  ){
            new Thread(()->{
              zi.derNum();
            },"BB").start();
        }
    }
}

0 人点赞