对于多线程之间的通讯的理解

老规矩,直接贴代码

package packageExercise;

public class Demo1 {
public static void main(String[] args) {
    Niuroumian product = new Niuroumian();
    Mianguan producer = new Mianguan(product);
    Shike customer = new Shike(product);
    producer.start();
    customer.start();
}
}

//牛肉面类
class Niuroumian{
    String name;//名字
    int price;//价格
    int flag = 0;
}
//面馆类
class Mianguan extends Thread{
    Niuroumian product;//牛肉面
    int i = 0;
    public Mianguan(Niuroumian product) {
        this.product = product;
    }
    public void run() {
    while(true){
        synchronized (product) {
            if(product.flag == 0){
            if(i % 2 == 0){
                product.name = "大碗牛肉面";
                try {
                    sleep(1);//此处让面馆线程睡1毫秒,增大线程出现安全问题的概率,
                } catch (InterruptedException e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }
                product.price = 10;
            }else{
                product.name = "小碗牛肉面";
                product.price = 5;
            }
            i++;
            System.out.println("面馆拉好了" + product.name + product.price);
            product.flag = 1;
            product.notify();
            }else{
                try {
                    product.wait();
                } catch (InterruptedException e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }
            }
            }
    } 
    }
}
//食客类
class Shike extends Thread{
    Niuroumian product;
    public Shike(Niuroumian product) {
        this.product = product;
    }

    public void run() {
        while(true){                
                synchronized (product) {
                    if (product.flag == 1) {
                    System.out.println("食客吃完了" + product.name + product.price);
                    product.flag = 0;
                    product.notify();

                    }
                    else{
                        product.notify();
                    }
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值