1,微波炉是一个对象,它应该是一个公共对象,大家都可以用。
2,注意物品正加热时不能开门,我们可以理解,这个对象在执行时,是排它的,唯一的
3,带皮带壳食物不能被加热。这个对象不是万能的,有些事它是不可以做的。
因此,我们的对象是公共对象,它有一个开关(属性),同时有开关方法,并且是单例程序,并且有同步约束,在方法体里加一些判断, 这个过程就OK了。
以上分析来自于一个帖子,参考以上我自己实现了一下代码,不过也加入我个人的理解
根据题意可以写一个食物的类,它只有一个属性,有活着没有壳:
view plaincopy to clipboardprint?
class Food {
public boolean isSheel = false;
public Food(boolean sheel) {
this.isSheel = sheel;
}
}
class Food {
public boolean isSheel = false;
public Food(boolean sheel) {
this.isSheel = sheel;
}
}
需要一个微波炉的类,它封装所有的方法和属性,只提供一个public 的构造函数,但是让它实现runnable接口,以从事它应该做的工作 - cook:
view plaincopy to clipboardprint?
public class Microwave implements Runnable {
private Food food;
public int time;
public Microwave(Food food, int time) {
this.food = food;
this.time = time;
}
@Override
public void run() {
cook(food, 3000);
}
private synchronized void cook(Food food, int time) {
close();
if (food.isSheel) {
System.out
.println("this microwave is not available for Food with sheels!");
return;
}
System.out.println("cooking ....");
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("food is OK!");
open();
}
private void close() {
System.out.println("door is closed. ");
}
private void open() {
System.out.println("door is opened. ");
}
public static void main(String[] args) {
Microwave mw = new Microwave(new Food(false), 2000);
new Thread(mw).start();
new Thread(mw).start();
}
}
public class Microwave implements Runnable {
private Food food;
public int time;
public Microwave(Food food, int time) {
this.food = food;
this.time = time;
}
@Override
public void run() {
cook(food, 3000);
}
private synchronized void cook(Food food, int time) {
close();
if (food.isSheel) {
System.out
.println("this microwave is not available for Food with sheels!");
return;
}
System.out.println("cooking ....");
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("food is OK!");
open();
}
private void close() {
System.out.println("door is closed. ");
}
private void open() {
System.out.println("door is opened. ");
}
public static void main(String[] args) {
Microwave mw = new Microwave(new Food(false), 2000);
new Thread(mw).start();
new Thread(mw).start();
}
}
注:为了方便,我直接在这个类中写了main方法,其实应该在重写一个测试类的,偷懒一下。。。
代码很简单,就不做解释了
程序运行输出结果:
view plaincopy to clipboardprint?
door is closed.
cooking ....
food is OK!
door is opened.
door is closed.
cooking ....
food is OK!
door is opened.
door is closed.
cooking ....
food is OK!
door is opened.
door is closed.
cooking ....
food is OK!
door is opened.