多线程奶箱案例

测试类

public class Test {
    public static void main(String[] args) {
        //创建公共资源
        Box b = new Box();

        //创建生产者对象,并将公共奶箱资源作为参数传递
        Producer p = new Producer(b);
        //同样创建消费者对象
        Customer c = new Customer(b);

        //创建两个对象对应的线程
        Thread t1 = new Thread(p);
        Thread t2 = new Thread(c);

        //启动线程
        t1.start();
        t2.start();
    }
}

生产者类

public class Producer implements Runnable {
    //创建奶箱成员变量,为后续对共享数据的操作做准备
    private Box b = new Box();

    //创建带参构造,方便将共享资源传入
    public Producer(Box b) {
        this.b = b;
    }

    //重写run()方法,实现不停调用放牛奶操作
    @Override
    public void run() {
        for (int i = 1; i < 30; i++) {
            b.put(i);
        }
    }
}

消费者类

public class Customer implements Runnable{
    private Box b = new Box();
    public Customer(Box b) {
        this.b = b;
    }

    @Override
    public void run() {
        while (true){
            b.get();
        }
    }
}

奶箱类,即公共资源

package milkThread;

public class Box {
    private int milk;
    //判断奶箱中是否有牛奶的状态参数
    private boolean state = false;

//    sleep()方法和notify()方法一般配合synchronized同步代码块使用 ,不然会报错
    public synchronized void put(int milk){
        //若奶箱中还有牛奶,则等待
        if (state){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //没有牛奶则执行放入牛奶操作,并将奶箱状态重置,并且唤醒另外一个线程
        this.milk = milk;
        System.out.println("放入第"+this.milk+"瓶奶");
        state = true;
        notify();
    }

    public synchronized void get(){
        if (!state){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("拿出第"+this.milk+"瓶奶");
        state =false;
        notify();
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值