模拟妈妈做饭,做饭时发现没有盐了,让儿子去买盐 。只有盐买回来之后,妈妈才能继续做饭的过程。

这是一道面试题,自己也做了一下

问题分析:从这个题目可以看出,有三个对象(妈妈,儿子和盐),其中盐是共享对象

代码实现如下:

package com.thread;

/**
 * 妈妈炒菜,儿子买盐,必须有时刻以上的盐,妈妈才能开始炒菜,否则儿子就要去买盐
 * 问题分析:这里有三个对象(儿子,妈妈和盐),其中盐是共享对象
 */
class Salt{
    int saltnum=0;
    public synchronized int subsalt() {
        if(saltnum<10){
            System.out.println("盐不够用了,儿子要去买盐!");
            try{
                this.wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        this.notify();
        System.out.println("儿子买盐回来了!");
        saltnum=saltnum-10;
        System.out.println("妈妈煮菜用了10克盐!");
        return saltnum;
    }
    public synchronized int addsalt() {
        if(saltnum>=10){
            System.out.println("还有盐,暂时不需要买!");
            try{
                this.wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        this.notify();
        System.out.println("买盐需要10秒钟!");
        try{
            Thread.sleep(10);
        }catch(InterruptedException e){
            e.printStackTrace();
        }
        System.out.println("盐买回来了!");
        saltnum=saltnum+10;
        return saltnum;
    }
}

    class Mother implements Runnable{
        Salt salt;
        public Mother(Salt salt) {
            this.salt=salt;
        }
        public void run() {
            System.out.println("妈妈炒菜要10秒钟");
            try{
                Thread.sleep(10);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            salt.subsalt();
        }
    }
    
     class Son implements Runnable{
         Salt salt;
         public Son(Salt salt) {
            this.salt=salt;
        }
         public void run() {
            System.out.println("儿子买盐要10秒钟");
            try{
                Thread.sleep(10);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            salt.addsalt();
        }
     }

public class Three {
         public static void main(String[] args) {
            Salt salt=new Salt();
            Mother mother=new Mother(salt);
            Son son=new Son(salt);
            new Thread(son).start();
            new Thread(mother).start();
        }
    }

运行结果:
  妈妈炒菜要10秒钟
  儿子买盐要10秒钟
  盐不够用了,儿子要去买盐!
  买盐需要10秒钟!
  盐买回来了!
  儿子买盐回来了!
  妈妈煮菜用了10克盐!

原文地址:https://www.cnblogs.com/xinxinjava/p/3068525.html