生产者/消费者问题

public class Factory {
    public int num=0;
    public static void main(String[] args) {
        Factory factory=new Factory();
        Producer producer=new Producer(factory);
        Comsumer comsumer=new Comsumer(factory);
        Thread t1=new Thread(producer,"生产者");
        Thread t2=new Thread(comsumer,"消费者");
        t1.start();
        t2.start();
    }
    public synchronized void product() {
        notifyAll();
        num++;
        System.out.println(""+Thread.currentThread().getName()+"正在生产第"+num+"个产品");
    }
    public synchronized void consume() {
        if(num>0){
            System.out.println(""+Thread.currentThread().getName()+"正在消费第"+num+"个产品");
            num--;
        }else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class Producer implements Runnable{
    private Factory factory;
    public Producer(Factory factory) {
        this.factory = factory;
    }
    @Override
    public void run() {
        while (true){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            factory.product();
        }
    }
}
class Comsumer implements Runnable{
    private Factory factory;
    public Comsumer(Factory factory) {
        this.factory = factory;
    }
    @Override
    public void run() {
        while (true){
            try {
                Thread.sleep(2500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            factory.consume();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值