java设计模式之消费者和生产者模式

消费者模式

题目简介:在一个街道上有车,有人,有红绿灯,当是绿灯时人走西北道路,当是红灯时车走南北道路

public class Demo01 {
    public static void main(String[] args) {
        Street street = new Street();
        //人线程和车线程走在一个街道对象
        Thread th1 = new Thread(new Car(street));
        Thread th2 = new Thread(new Person(street));
        th1.start();
        th2.start();
    }
}
class Street{
    //红绿灯 true为绿灯false为红灯
    boolean flag = false;
    //人走的西北方向的路
    public synchronized void ws(){
        if (flag){
            System.out.println("人在走");
            flag = false;
        }
        //将当前对象的线程池中的线程唤醒
        this.notify();
        try {
            //将当前对象的线程等待
            this.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public synchronized void  ne(){
        if (!flag) {
            System.out.println("车在走!");
            flag = true;
        }
        this.notify();
        try {
            this.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
//车线程
class Car implements Runnable{
    private Street street;
    //街道对象
    public Car(Street street) {
        this.street = street;
    }
    @Override
    public void run() {
        while (true){
            street.ne();
    }
    }
}
//人线程
class Person implements Runnable{
    private Street street;
    public Person(Street street) {
        this.street = street;
    }
    @Override
    public void run() {
        while (true){
            street.ws();
        }
    }
}

上述代码为简单的消费者和生产者模式

注意notify和wait只能同步的情况下实现

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值