模拟多线程 看了视频终于做出来了 不知道这样做是否可以 求大神指导
模拟妈妈做饭,做饭时发现没有盐了,让儿子去买盐(假设买盐需要3分钟), 只有盐买回来之后,妈妈才能继续做饭的过程- public class Test10 {
- /**
- * @param args
- *
- *
- */
- public static void main(String[] args) {
- Salt salt = new Salt();
- Mother m = new Mother(salt);
- Son s = new Son(salt);
- Thread t1 = new Thread(m);
- Thread t2 = new Thread(s);
- t1.start();
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- t2.start();
- }
- }
- class Salt {
- boolean falg = true;
- }
- class Mother implements Runnable {
- private Salt salt;
- Mother(Salt salt) {
- this.salt = salt;
- }
- public void run() {
- synchronized (salt) {
- System.out.println("Mother Cooking");
- if (salt.falg) {
- System.out.println("Son Buy Salt");
- try {
- salt.wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- System.out.println("Mother Cook");
- salt.notify();
- }
- }
- }
- class Son implements Runnable {
- private Salt salt;
- Son(Salt salt) {
- this.salt = salt;
- }
- public void run() {
- synchronized (salt) {
- if (!salt.falg) {
- try {
- salt.wait();
- } catch (InterruptedException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- System.out.println("Buy Salt");
- try {
- Thread.sleep(3 * 60000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- salt.falg = true;
- salt.notifyAll();
- }
- }
- }
复制代码 |