本帖最后由 李慧声 于 2013-4-8 10:18 编辑
- <div class="blockcode"><blockquote>package com.itheima;
- /**
- * 第10题: 模拟妈妈做饭,做饭时发现没有盐了,
- * 让儿子去买盐(假设买盐需要3分钟),只有盐买回来之后,妈妈才能继续做饭的过程。
- * @author Lihsh
- *
- */
- public class Test10 {
- /**
- * 测试类实现主方法,用来测试程序
- * @param args
- */
- public static void main(String[] args) {
- new Thread(new MotherCooking("Mom" , false)).start(); //mum做饭
- }
- }
- /**
- * 思路:Mum在做饭,发现没盐了,调动儿子的线程,去买盐;
- * 此时,调用son的join()方法,让mum的线程在儿子的线程执行结束之后再执行。
- * @author Lihsh
- *
- */
- class MotherCooking implements Runnable{
- private boolean hasSalt;
- private String name;
- public MotherCooking(String name , boolean hasSalt) {
- this.name = name;
- this.hasSalt = hasSalt;
- }
- @Override
- public void run() {
- System.out.println("Mother is cooking...");
- while(!hasSalt) { //no salt is true
- System.out.println("Jim , come here and help mum to buy some salt... ");
- //调用son,让son去买盐
- try {
- Thread t1 = new Thread(new SonBuySalt("Jim",false));
- t1.start();
- t1.join();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- hasSalt = true;
- }
- if(hasSalt){ //买的盐的话,那就接着做饭,(能成循环中跳出来,那自然就是买到盐了 hasSalt is true)
- System.out.println("Thanks ,I will continue to cook...");
- }
- }
- }
- /**
- * 描述:son买盐的功能类,当Mum调用时启动。
- * 通过标志位isBuyed(是否买的盐)来控制线程的执行。
- * @author Lihsh
- *
- */
- class SonBuySalt implements Runnable {
- private String name;
- private boolean isBuyed;//买到盐与否
-
- public SonBuySalt(){}
- public SonBuySalt(String name , boolean isBuyed)
- {
- this.name = name;
- this.isBuyed = isBuyed;
- }
- @Override
- public void run() {
- System.out.println("OK , Mum!"); //去买盐了
- while(!isBuyed){
- try {
- Thread.sleep(3 * 60 * 1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- isBuyed = true;
- }
- if(isBuyed){
- System.out.println("Mum , I have bought salt...");
- }
- }
- }
复制代码 运行结果:
Mother is cooking...
Jim , come here and help mum to buy some salt...
OK , Mum!
Mum , I have bought salt...
Thanks ,I will continue to cook...
好像逻辑就应该是这样的吧,我是不敢确定,求同志门指点!
更新了一下代码。
|