模拟:小孩在睡觉,醒来后给小孩喂奶
方式一:父亲监控小孩,小孩一醒就喂奶
/** * 模拟小孩睡觉,醒来后喂奶 * */ class Dad implements Runnable{ private Child c; public Dad(Child c){ this.c=c; } private void feed(){ System.out.println("给小孩喂奶。。。"); } @Override public void run() { while(!c.isWakeUp()){ try { System.out.println("还没醒。。。"); Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } feed(); } } class Child implements Runnable{ private boolean isWakeUp=false; void wakeUp(){ isWakeUp=true; System.out.println("小孩醒来了。。。。。。"); } public boolean isWakeUp() { return isWakeUp; } public void setWakeUp(boolean isWakeUp) { this.isWakeUp = isWakeUp; } @Override public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } wakeUp(); } } public class Test { public static void main(String[] args){ Child c=new Child(); new Thread(c).start(); new Thread(new Dad(c)).start(); } }方式二:小孩醒了,叫爸爸喂奶
class Dad { void feed(){ System.out.println("给小孩喂奶。。。"); } } class Child implements Runnable{ private Dad dad; public Child(Dad dad){ this.dad=dad; } void wakeUp(){ System.out.println("小孩醒来了,喊爸爸喂奶。。。"); dad.feed(); } @Override public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } wakeUp(); } } public class Test { public static void main(String[] args){ Dad d=new Dad(); new Thread(new Child(d)).start(); } }