生产者消费者问题

图片说明
代码:

package face_duixiang_first;
public class Test {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Thread productorthread = new Thread(new Productor(clerk));
        Thread consumerthread = new Thread(new Consumer(clerk));
        productorthread.start();
        consumerthread.start();
        Thread productorthread2 = new Thread(new Productor(clerk));
        Thread consumerthread2 = new Thread(new Consumer(clerk));
        productorthread2.start();
        consumerthread2.start();
    }
}

//售货员类
class Clerk{
    private int product = 0;
    public synchronized void addProduct() {
        if(product >= 20) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        else {
            product++;
            System.out.println("生产者正在生产第" + product + "件产品");
            notifyAll();
        }
    }
    public synchronized void getProduct() {
        if(this.product <= 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        else {
            System.out.println("消费者正在消费第" + product + "件产品");
            product--;
            notifyAll();
        }
    }
}

//生产者
class  Productor implements Runnable{
    Clerk clerk;
    public Productor(Clerk clerk) {
        super();
        this.clerk = clerk;
    }
    @Override
    public void run() {
        while(true) {
            System.out.println("生产者开始生产产品");
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.addProduct();
        }
    }
}
// 消费者
class  Consumer implements Runnable{
    Clerk clerk;
    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }
    @Override
    public void run() {
        System.out.println("消费者开始取走产品");
        while(true) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            clerk.getProduct();
        }
    }
}
全部评论

相关推荐

吃不饱的肱二头肌很想退休:tnnd 我以为选妹子呢,亏我兴高采烈的冲进来😠
投递快手等公司10个岗位
点赞 评论 收藏
分享
点赞 1 评论
分享
牛客网
牛客企业服务