6.JUC-线程的虚假唤醒-生产者和消费者

一)经典案例生产者和消费者

存在问题:
在经典的案例生产者和消费者中存在了一个很大的问题,当生产者生产的消息过快或者是消费者消费的消息过快容易出现数据丢失的问题。

解决方法:等待唤醒机制

演示生产者消费者案例

/**
 * @project_name:juc
 * @date:2019/9/27:21:06
 * @author:shinelon
 * @Describe:生产者和消费者案例
 */
public class TestProductAndConsumer
{
    public static void main(String[] args)
    {
        Check check = new Check();
        Product product = new Product(check);
        Consumer consumer = new Consumer(check);
        new Thread(product,"生产者A").start();
        new Thread(consumer,"消费者B").start();
    }
}

class Check
{

    private int product = 0;

    /**
     * 添加商品
     */
    public synchronized void add()
    {
        if (product >=20)
        {
            System.out.println("商品已满");
            try
            {
                this.wait();
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        else
        {
            System.out.println(Thread.currentThread().getName() + "增加商品:" + ++product);
            this.notifyAll();
        }
    }


    /**
     * 消费
     */
    public synchronized void reduce()
    {
        if (this.product <= 0)
        {
            System.out.println("商品以空");
            try
            {
                this.wait();
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        else
        {
            System.out.println(Thread.currentThread().getName() + "目前正在消费:" + --product);
            this.notifyAll();
        }
    }
}

/**
 * 生产者
 */
class Product implements Runnable
{
    private Check check;

    public Product(Check check)
    {
        this.check = check;
    }


    @Override
    public void run()
    {
        for (int i = 0; i < 20; i++)
        {
            this.check.add();
        }
    }
}

/**
 * 消费者
 */
class Consumer implements Runnable
{
    private Check Check;

    public Consumer(Check Check)
    {
        this.Check = Check;
    }

    @Override
    public void run()
    {
        for (int i = 0; i < 20; i++)
        {

            this.Check.reduce();
        }
    }
}

在这里插入图片描述

二)虚假唤醒的演示

演示虚假唤醒之间需要先演示的一个的线程不结束的问题
1.给生产者加上0.2秒的延迟
2.给生产的数量改为1

/**
 * @project_name:juc
 * @date:2019/9/27:21:06
 * @author:shinelon
 * @Describe:生产者和消费者案例
 */
public class TestProductAndConsumer
{
    public static void main(String[] args)
    {
        Check check = new Check();
        Product product = new Product(check);
        Consumer consumer = new Consumer(check);
        new Thread(product,"生产者A").start();
        new Thread(consumer,"消费者B").start();
    }
}

class Check
{
    private int product = 0;

    /**
     * 添加商品
     */
    public synchronized void add()
    {
        if (product >=1)
        {
            System.out.println("商品已满");
            try
            {
                this.wait();
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        else
        {
            System.out.println(Thread.currentThread().getName() + "增加商品:" + ++product);
            this.notifyAll();
        }
    }


    /**
     * 消费
     */
    public synchronized void reduce()
    {
        if (this.product <= 0)
        {
            System.out.println("商品以空");
            try
            {
                this.wait();
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        else
        {
            System.out.println(Thread.currentThread().getName() + "目前正在消费:" + --product);
            this.notifyAll();
        }
    }
}

/**
 * 生产者
 */
class Product implements Runnable
{
    private Check check;

    public Product(Check check)
    {
        this.check = check;
    }


    @Override
    public void run()
    {
        for (int i = 0; i < 20; i++)
        {
            try
            {
                Thread.sleep(200);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            this.check.add();
        }
    }
}

/**
 * 消费者
 */
class Consumer implements Runnable
{
    private Check Check;

    public Consumer(Check Check)
    {
        this.Check = Check;
    }

    @Override
    public void run()
    {
        for (int i = 0; i < 20; i++)
        {
            this.Check.reduce();
        }
    }
}

出现程序不能够正常的结束

在这里插入图片描述

原因分析:

根据上面的分析首先生产者线程要比消费者线程要慢,假设此时生产者线程剩下2次循环的机会,消费者线程只剩下1次的机会,那么消费者线程在消费完毕后线程结束,而生产者线程在商品大于等于1的时候进入了wait(),此时消费者线程已经结束那么没有线程在去消费商品。

解决的办法把else去掉,这样在等待时候会执行线程的唤醒,不会因为线程不满足条件而不进行线程的唤醒

/**
 * @project_name:juc
 * @date:2019/9/27:21:06
 * @author:shinelon
 * @Describe:生产者和消费者案例
 */
public class TestProductAndConsumer
{
    public static void main(String[] args)
    {
        Check check = new Check();
        Product product = new Product(check);
        Consumer consumer = new Consumer(check);
        new Thread(product, "生产者A").start();
        new Thread(consumer, "消费者B").start();
    }
}

class Check
{
    private int product = 0;

    /**
     * 添加商品
     */
    public synchronized void add()
    {
        if (product >= 1)
        {
            System.out.println("商品已满");
            try
            {
                this.wait();
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        //去掉else保证线程的正确执行
        System.out.println(Thread.currentThread().getName() + "增加商品:" + ++product);
        this.notifyAll();
    }


    /**
     * 消费
     */
    public synchronized void reduce()
    {
        if (this.product <= 0)
        {
            System.out.println("商品以空");
            try
            {
                this.wait();
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
           //去掉else保证线程的正确执行
        System.out.println(Thread.currentThread().getName() + "目前正在消费:" + --product);
        this.notifyAll();
    }
}

/**
 * 生产者
 */
class Product implements Runnable
{
    private Check check;

    public Product(Check check)
    {
        this.check = check;
    }


    @Override
    public void run()
    {
        for (int i = 0; i < 20; i++)
        {
            try
            {
                Thread.sleep(200);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            this.check.add();
        }
    }
}

/**
 * 消费者
 */
class Consumer implements Runnable
{
    private Check Check;

    public Consumer(Check Check)
    {
        this.Check = Check;
    }

    @Override
    public void run()
    {
        for (int i = 0; i < 20; i++)
        {
            this.Check.reduce();
        }
    }
}

正常结束:

在这里插入图片描述

2)虚假唤醒演示

现在线程中只用一个生产者和一个消费者线程,线程之间还是很和谐的假如现在分别增加一个生产者和消费者线程

/**
 * @project_name:juc
 * @date:2019/9/27:21:06
 * @author:shinelon
 * @Describe:生产者和消费者案例
 */
public class TestProductAndConsumer
{
    public static void main(String[] args)
    {
        Check check = new Check();
        Product product = new Product(check);
        Consumer consumer = new Consumer(check);
     
        new Thread(product, "生产者A").start();
        new Thread(consumer, "消费者B").start();
        new Thread(product, "生产者C").start();
        new Thread(consumer, "消费者D").start();
    }
}

class Check
{
    private int product = 0;

    /**
     * 添加商品
     */
    public synchronized void add()
    {
        if (product >= 1)
        {
            System.out.println("商品已满");
            try
            {
                this.wait();
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        //去掉else保证线程的正确执行
        System.out.println(Thread.currentThread().getName() + "增加商品:" + ++product);
        this.notifyAll();
    }


    /**
     * 消费
     */
    public synchronized void reduce()
    {
        if (this.product <= 0)
        {
            System.out.println("商品以空");
            try
            {
                this.wait();
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }

        System.out.println(Thread.currentThread().getName() + "目前正在消费:" + --product);
        this.notifyAll();
    }
}

/**
 * 生产者
 */
class Product implements Runnable
{
    private Check check;

    public Product(Check check)
    {
        this.check = check;
    }


    @Override
    public void run()
    {
        for (int i = 0; i < 20; i++)
        {
            try
            {
                Thread.sleep(200);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            this.check.add();
        }
    }
}

/**
 * 消费者
 */
class Consumer implements Runnable
{
    private Check Check;

    public Consumer(Check Check)
    {
        this.Check = Check;
    }

    @Override
    public void run()
    {
        for (int i = 0; i < 20; i++)
        {
            this.Check.reduce();
        }
    }
}

测试结果就发现此时已经出现问题。

在这里插入图片描述

虚假唤醒的原因分析:

线程在执行的时候生产者和消费者都有两个的线程在进行共享资源的操作,当线程进行操作的时候假设现在消费者BD同时进入了方法内,假设此时B线程失去执行权的话那么在进行D执行消费商品后,线程B获得了执行权继续执行此时依然会在对商品进行消费,按照正常逻辑需要线程B在去判断下是否商品已经没了,如果不对商品进行判断就会出现虚假消费出现负值。这就是虚假唤醒。

虚假唤醒在JDK的帮助帮助文档内是有解决方案的,就是wait()方法的解释下

(有兴趣小伙伴可以去认证下)官方给出的是使用while循环进行解决。将wait()出现在while中

package com.itguigu.juc;


/**
 * @project_name:juc
 * @date:2019/9/27:21:06
 * @author:shinelon
 * @Describe:生产者和消费者案例
 */
public class TestProductAndConsumer
{
    public static void main(String[] args)
    {
        Check check = new Check();
        Product product = new Product(check);
        Consumer consumer = new Consumer(check);
        new Thread(product, "生产者A").start();
        new Thread(consumer, "消费者B").start();
        new Thread(product, "生产者C").start();
        new Thread(consumer, "消费者D").start();
    }
}

class Check
{
    private int product = 0;

    /**
     * 添加商品
     */
    public synchronized void add()
    {

        //解决线程的虚假唤醒,将wait()始终出现在while循环中。
        while (product >= 1)
        {
            System.out.println("商品已满");
            try
            {
                this.wait();
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        //去掉else保证线程的正确执行
        System.out.println(Thread.currentThread().getName() + "增加商品:" + ++product);
        this.notifyAll();
    }


    /**
     * 消费
     */
    public synchronized void reduce()
    {
        while (this.product <= 0)
        {
            System.out.println("商品以空");
            try
            {
                this.wait();
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }

        System.out.println(Thread.currentThread().getName() + "目前正在消费:" + --product);
        this.notifyAll();
    }
}

/**
 * 生产者
 */
class Product implements Runnable
{
    private Check check;

    public Product(Check check)
    {
        this.check = check;
    }


    @Override
    public void run()
    {
        for (int i = 0; i < 20; i++)
        {
            try
            {
                Thread.sleep(200);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            this.check.add();
        }
    }
}

/**
 * 消费者
 */
class Consumer implements Runnable
{
    private Check Check;

    public Consumer(Check Check)
    {
        this.Check = Check;
    }

    @Override
    public void run()
    {
        for (int i = 0; i < 20; i++)
        {
            this.Check.reduce();
        }
    }
}

线程正常结束

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值