生产者与消费者

notify() 唤醒一个进程
wait() 阻塞一个进程
synchronized 同步锁,修饰代码块和方法均可
wait和notify必须在synchronized块中,否则会抛出IllegalMonitorStateException

/**
 * 要求 缓存区满后生产者不能生产,缓存区空后消费者不再消费,缓存区不满不空消费者可以消费,生产者可以生产
 *
 * ProducerAndCustomer类 count记录缓冲区有几个物品 ;producerAndCustomer它是实例负责被两个线程类调用
 * 最开始想的是线程run方法单独写,失败了。但要实现线程通信需要线程之间共享一个缓冲区
 * 注意的一点是while循环需要放在synchronized外面,不然只能同步,不能异步。
 * 最好另设一个类带替代ProducerAndCustomer的共享作用
 *
 * 2022-06-14 15:22
 */

class Producer extends Thread {
    ProducerAndCustomer producerAndCustomer;
    Producer(ProducerAndCustomer producerAndCustomer){
            this.producerAndCustomer = producerAndCustomer;
    }
    @Override
    public void run() {
        while (true){
            producerAndCustomer.product(getName());

        }
    }
}
class Consumer extends Thread {
    ProducerAndCustomer producerAndCustomer;
    Consumer(ProducerAndCustomer producerAndCustomer){
        this.producerAndCustomer = producerAndCustomer;
    }
    @Override
    public void run() {
        while (true){

            producerAndCustomer.consume(getName());
        }
    }
}
public class ProducerAndCustomer {
    private  int count = 0;
    static ProducerAndCustomer producerAndCustomer = new ProducerAndCustomer();
    public static void main(String[] args) {
        new Producer(producerAndCustomer).start();
        new Consumer(producerAndCustomer).start();
    }
    synchronized void product(String name) {
            if (count > 20) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println(name + "生产第" + count + "个产品");
            count++;
            notify();
    }
    synchronized void consume(String name) {
            if (count <= 0) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println(name + "消费第" + count + "个产品");
            count--;
            notify();
    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值