多线程通信问题

 用到的方法:

//Object类等待和唤醒方法
//导致当前线程等待它被唤醒,通常是 通知或 中断 。 
void wait()
//导致当前线程等待它被唤醒,通常是 通知或 中断 ,或者直到经过一定量的实时。      
void wait•(long timeoutMillis) 
// 导致当前线程等待它被唤醒,通常是 通知或 中断 ,或者直到经过一定量的实时。 
void wait•(long timeoutMillis, int nanos)
// 唤醒正在此对象监视器上等待的单个线程。     
void notify()  //唤醒一个或多个中随机的一个   
//唤醒等待此对象监视器的所有线程。     
void notifyAll()   //唤醒全部  

厨师-—服务员—做菜端菜代码示例 : 

public class Practice {
    public static void main(String[] args) {
        Food f = new Food();
        new Cook(f).start();
        new Waiter(f).start();
​
    }
​
    static class Cook extends Thread {
        private Food f;
​
        public Cook(Food f) {
            this.f = f;
        }
​
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                if (i % 2 == 0) {
                    f.setNameAndTaste("皮蛋粥", "咸");
                } else {
                    f.setNameAndTaste("雪糕", "甜");
                }
            }
        }
    }
​
    static class Waiter extends Thread {
        private Food f;
​
        public Waiter(Food f) {
            this.f = f;
        }
​
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                f.get();
            }
​
        }
    }
​
    static class Food {
        private String name;
        private String taste;
        private Boolean flag = true;
​
        public synchronized void setNameAndTaste(String name, String taste) {
            if (flag) {
                this.name = name;
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                this.taste = taste;
                flag = false;
                this.notifyAll();
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
​
        public synchronized void get() {
            if (!flag) {
                System.out.println("服务员端走的菜的名字是:" + name + "味道是:" + taste);
                flag = true;
                this.notifyAll();
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值