生产者与消费者案例

实现消费者与生产者
生产者:生产一个产品,当被消费者消费后才会生产下一个产品;
消费者:消费一个产品,当生产者生产出一个产品后,才可消费;
创建一个产品类;
一个生产者线程;
一个消费者线程;
实现线程同步,两个线程都操作了产品类,应该在产品类中设置synchronized关键字;
使用等待与唤醒操作,实现同步:
Object类

public final void wait​()throws InterruptedException //等待:死等
public final void wait​(long timeout) throws InterruptedException //设置等待时间
public final void wait​(long timeout,int nanos) throws InterruptedException //设置等待时间

public final void notify​() //唤醒第一个等待线程
public final void notifyAll​() //唤醒全部等待线程
/**
 * 设置生产消费标记
 * symbol,当symbol为true时,允许生产,不允许消费;
 * 当symbol为false,允许消费,不允许生产;
 */
class Message
{
    private String name;
    private String character;
    private boolean symbol=true;


    public synchronized String get() {
        if(symbol)//还未生产;
        {
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        finally {
            this.symbol=true;
            super.notify();
        }

        return this.name+"*********"+this.character;
    }

    public synchronized void set(String name,String character) {
        if(!symbol)
        {
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.name=name;
        this.character = character;
        this.symbol=false;//已经生产过了;
        super.notify();//唤醒等待线程;
    }
}

class Product implements Runnable{
    private Message mes;

    public Product(Message mes)
    {
        this.mes=mes;
    }

    @Override
    public void run() {
        for(int i=0;i<100;i++)
        {
            if(i%2==00)
            {
                this.mes.set("杨幂","演技差");
            }
            else
            {
                this.mes.set("陈坤","演技好");
            }
        }
    }
}

class Customer implements  Runnable
{
    private Message mes;
    public Customer(Message mes)
    {
        this.mes=mes;
    }

    @Override
    public void run() {
        for(int i=0;i<100;i++)
        {
            System.out.println(this.mes.get());
        }
    }
}
public class ProductCustomer {


    public static void main(String[] args) {
        Message mes=new Message();
        new Thread(new Product(mes)).start();
        new Thread(new Customer(mes)).start();
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值