现在的位置: 首页 > 综合 > 正文

多线程之儿子买盐问题

2012年11月11日 ⁄ 综合 ⁄ 共 1700字 ⁄ 字号 评论关闭

  刚刚看到了一关于多线程的面试题目,就试着写了一下。

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

  问题分析:既然是面向对象编程,拿到问题是首先就要分析涉及到哪些对象。显然,该问题涉及的对象有:妈妈、儿子和盐。其中妈妈和儿子都是线程类,共享资源就是盐,所以盐Salt类的方法都要设置为同步方法。具体代码如下:

 1 package com.sync;
 2 /**
 3  * 题目: 模拟妈妈做饭,做饭时发现没有盐了,让儿子去买盐
 4  *       只有盐买回来之后,妈妈才能继续做饭的过程。
 5  * @author Administrator
 6  *
 7  */
 8 
 9 //
10 class Salt{
11     private int saltNum=0; //盐的数量,假设开始没有盐
12     
13     //煮菜需要食用盐,假设煮一个菜需要10克盐
14     public synchronized int subSalt(){
15         while(saltNum<=0){ //盐没有了,则需要等待
16             System.out.println("盐不够了,等待中.....");
17             try {
18                 this.wait();
19             } catch (InterruptedException e) {
20                 e.printStackTrace();
21             }
22         }
23         notify();
24         saltNum = saltNum - 10;
25         System.out.println("妈妈煮菜使用了10克盐!剩余"+saltNum+"克盐!");
26         return saltNum;
27     }
28     //买盐,每次买saltNum克盐
29     public synchronized void addSalt(int num){
30         while(saltNum>=10){ //还有盐,暂时不需要买
31             try {
32                 this.wait();
33             } catch (InterruptedException e) {
34                 e.printStackTrace();
35             }
36         }
37         try { //假设买盐需要10秒钟
38             Thread.sleep(10000);
39         } catch (InterruptedException e) {
40             e.printStackTrace();
41         }
42         saltNum = saltNum + num;
43         System.out.println("儿子买回来100克盐!");
44         notify();//买完盐回来后,唤醒正在等待的母亲继续煮菜
45     }
46 }
47 
48 //母亲
49 class Mother implements Runnable{
50     private Salt salt;
51     public Mother(Salt salt) {
52         this.salt = salt;
53     }
54     public void run() {
55         while(true){
56             salt.subSalt();
57             try {
58                 Thread.sleep(2000);
59             } catch (InterruptedException e) {
60                 e.printStackTrace();
61             }
62         }
63     }
64     
65 }
66 
67 //儿子
68 class Son implements Runnable{
69     private Salt salt;
70     public Son(Salt salt) {
71         this.salt = salt;
72     }
73     public void run() {
74         while(true){
75             try {
76                 Thread.sleep(3000);
77             } catch (InterruptedException e) {
78                 e.printStackTrace();
79             }
80             salt.addSalt(100);
81         }
82     }
83     
84 }
85 
86 public class SaltAndCook {
87 
88     public static void main(String[] args) {
89         Salt salt = new Salt();
90         Mother m = new Mother(salt);
91         Son son = new Son(salt);
92         new Thread(m).start();
93         new Thread(son).start();
94     }
95 
96 }

 

【上篇】
【下篇】

抱歉!评论已关闭.