请用程序模拟下列情形:
小孩在睡觉
醒来后要求吃东西
需求分析。弄清楚要做什么。
设计。怎么去实现这些功能。实现功能的方法有很多,有的好,有的坏。
设计方案一:
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
child c = new child();
new Thread(c).start();
new Thread(new Dad(c)).start();
}
}
class child implements Runnable{
private boolean wakenup = false; //默认是睡着的状态
int time;
public void wakeUp(){
wakenup = true;
}
public boolean isWakenup() {
return wakenup;
}
public void setWakenup(boolean wakenup) {
this.wakenup = wakenup;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.wakeUp();
}
}
class Dad implements Runnable{
private child c;
public Dad(child c){
this.c = c;
}
private void feed (child c2){
System.out.println("feed child");
}
public void run() {
while(!c.isWakenup()){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
feed(c);
}
}
这个方案存在浪费cpu资源的问题,如果小孩不醒,Dad线程会一直在那开着,而不能去干别的事情。