欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

一个初始值为0的变量,两个线程对其交替操作,一个加1一个减1,来5轮

程序员文章站 2022-03-09 19:01:32
...

 题目:一个初始值为0的变量,两个线程对其交替操作,一个加1一个减1,来5轮

class ShareData{
    private int number=0;
    private Lock lock=new ReentrantLock();
   /**
     * 1.一个Condition的实例必须与一个Lock绑定,Condition一般都是作为Lock的内部实现
     * 2.Condition与Lock配合可以实现等待/通知模式
     * 3.Condition接口也提供了类似Object的监视器方法
     */
    private Condition condition=lock.newCondition();

    public void increment() throws Exception{
        lock.lock();
        try {
            //1.判断
            while (number!=0){
                //等待,不能生产
                condition.await();
            }
            //2.干活
            number++;
            System.out.println(Thread.currentThread().getName()+"\t"+number);
            //3.通知唤醒
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void decrement() throws Exception{
        lock.lock();
        try {
            //1.必须要用while判断,防止虚假唤醒
            while (number==0){
                //等待,不能消费
                condition.await();
            }
            //2.干活
            number--;
            System.out.println(Thread.currentThread().getName()+"\t"+number);
            //3.通知唤醒
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
public class ProductConsumer_Traditional {
    public static void main(String[] args) {
        ShareData shareData=new ShareData();
        new Thread(()->{
            for (int i = 1; i <=5; i++) {
                try {
                    shareData.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"AA").start();

        new Thread(()->{
            for (int i = 1; i <=5; i++) {
                try {
                    shareData.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"BB").start();
    }
}

虚假唤醒?

源码:
As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop: 

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait();
         ... // Perform action appropriate to condition
     }
 

将上述代码中的线程数量再增加两个,将await放入if条件判断中,就会出现虚假唤醒,导致出错

相关标签: Lock