JAVA 多线程 生产者消费者问题(操作系统实验)


/**
 * 生产者消费者
 */
public class Demo02 {
    public static void main(String[] args) {
        //创建资源
        Resource r = new Resource();
        //创建生产者
        Producer producer1 = new Producer(r);
        Producer producer2 = new Producer(r);
        //创建消费者
        Consumer consumer1 = new Consumer(r);
        Consumer consumer2 = new Consumer(r);
        //创建线程
        Thread thread1 = new Thread(producer1);
        Thread thread2 = new Thread(producer2);
        Thread thread3 = new Thread(consumer1);
        Thread thread4 = new Thread(consumer2);
        //开启线程
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
    }
}
//资源类
class Resource{
    private String name;//资源名称
    private int number = 1;//编号
    private boolean flag = true;//是否消费
    //生产者生产资源
    public synchronized void set(String name){
        //可以消费,生产停止
        while (flag){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //开始生产
        this.name = name+ number;
        //编号自增
        number++;
        //生产完编号自增  以供下次使用
        System.out.println(Thread.currentThread().getName()+"正在生产:"+this.name);
        //修改标识开始消费
        flag = true;
        //唤醒所有线程
        this.notifyAll();
    }
    //消费者资源类
    public synchronized void get(){
        //不能消费
        while (!flag){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName()+"正在消费"+this.name);
        //修改标识,可以生产。
        flag=false;
        //唤醒所有线程
        this.notifyAll();
    }
}

//生产者
class Producer implements Runnable{
    private Resource r;

    public Producer(Resource r) {
        this.r = r;
    }
    //生产
    @Override
    public void run() {
        while (true){
            r.set("面条");
        }
    }
}

//消费者
class Consumer implements Runnable{
    private Resource r;

    public Consumer(Resource r) {
        this.r = r;
    }
    @Override
    public void run() {
        while (true){
            r.get();
        }
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值