多线程之儿子买盐问题

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

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

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

1 package com.sync; * 题目: 模拟妈妈做饭,做饭时发现没有盐了,让儿子去买盐 4 *只有盐买回来之后,妈妈才能继续做饭的过程。 Administrator 6 * Salt{saltNum=0; //盐的数量,虚拟主机,假设开始没有盐 subSalt(){System.out.println(“盐不够了,等待中…..”);17try {18this.wait();19} catch (InterruptedException e) {20 e.printStackTrace();21 }22 }23 notify();24saltNum = saltNum – 10;25System.out.println(“妈妈煮菜使用了10克盐!剩余”+saltNum+”克盐!”);26return saltNum;27 }addSalt(int num){ {32this.wait();33} catch (InterruptedException e) {34 e.printStackTrace();35 }36 }Thread.sleep(10000);39} catch (InterruptedException e) {40 e.printStackTrace();41 }42saltNum = saltNum + num;43System.out.println(“儿子买回来100克盐!”); }46 }Mother implements Runnable{50private Salt salt;51public Mother(Salt salt) {52this.salt = salt;53 } run() {55while(true){56 salt.subSalt();57try {58Thread.sleep(2000);59} catch (InterruptedException e) {60 e.printStackTrace();61 }62 }63 }6465 }Son implements Runnable{69private Salt salt;70public Son(Salt salt) {71this.salt = salt;72 } run() {74while(true){75try {76Thread.sleep(3000);77} catch (InterruptedException e) {78 e.printStackTrace();79 }80salt.addSalt(100);81 }82 }8384 } SaltAndCook { main(String[] args) {89Salt salt = new Salt();90Mother m = new Mother(salt);91Son son = new Son(salt);92new Thread(m).start();93new Thread(son).start();94 }95 96 }路灯和我之间,究竟谁是谁的过客,

多线程之儿子买盐问题

相关文章:

你感兴趣的文章:

标签云: