生产者消费者问题

一世执手 提交于 2020-02-08 17:54:21

 

 思路:

生产者判读是否大于20: 若 否,则生产一个产品并且唤醒(消费者).若是,则堵塞.

消费者判读是否大于0,若是,则消费一个产品,并唤醒(生产者).若否,则堵塞.

我们将生产和消费的方法,放到店员类,这样可以操作共享数据.

package com.LearnJava.Thread;
class Clerk {
    private int products=0;

    public synchronized void prodectOne(){
        if(products<20){
            products++;
            System.out.println(Thread.currentThread().getName()+"生产第"+products+"个产品");
            notifyAll();
        }else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public synchronized void consumeOne(){
        if(products>0){
            System.out.println(Thread.currentThread().getName()+"消费第"+products+"个产品");
            products--;
            notifyAll();
        }else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class Productor extends Thread{
    private Clerk c;
    Productor(Clerk c){
        this.c=c;
    }
    @Override
    public void run() {
        while (true){
            c.prodectOne();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class Customer extends Thread{
    private Clerk c;
    Customer(Clerk c){
        this.c=c;

    }
    @Override
    public void run() {
        while (true){
            c.consumeOne();

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class PCCProblem {
    public static void main(String[] args) {
        Clerk c = new Clerk();
        Productor p1 = new Productor(c);
        Productor p2 = new Productor(c);
        Customer c1 = new Customer(c);
        p1.start();
        p2.start();
        c1.start();






    }
}
View Code

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!