- Java code
public class T { public final String name; public final String food; public final String sound; public T(String name, String food, String sound) { this.name = name; this.food = food; this.sound = sound; } public void eat() { System.out.println(name + ": Mmmmm, " + food); } public void play() { System.out.println(name + ": " + sound + " " + sound); } public void sleep() { System.out.println(name + ": Zzzzzzz..."); } public void live() { new Thread() { @Override public void run() { while (true) { eat(); play(); // sleep(); // 如果用这个代替下面的语句,会如何? T.this.sleep(); } } }.start(); } public static void main(String[] args) { new T("Fido", "beef", "Woof").live(); }}
------解决方案--------------------
运行结果:
Fido: Mmmmm, beef
Fido: Woof Woof
Fido: Zzzzzzz...
不停循环。
如果将sleep替换掉下面那句,程序会报错:sleep() is not applicable for this argument.
------解决方案--------------------
理由:sleep()是自带的方法,这里如果直接写sleep()不会掉用自己写的sleep(),而会考虑调用thread.sleep(long)。
------解决方案--------------------
这是狗的生活 - 编译通过运行结果证明这是一只懒狗
下面的这个类模拟了一个家庭宠物的生活。main 方法创建了一个 T 实例,用它来表示一只名叫 Fido 的狗,然后让它运行。虽然绝大部分的狗都在后院里奔跑(run),这只狗却是在后台运行(run)。那么,这个程序会打印出什么呢?
- Java code
public class T { public final String name; public final String food; public final String sound; public T(String name, String food, String sound) { this.name = name; this.food = food; this.sound = sound; } public void eat() { System.out.println(name + ": Mmmmm, " + food); } public void play() { System.out.println(name + ": " + sound + " " + sound); } public void sleep() { System.out.println(name + ": Zzzzzzz..."); } public void live() { new Thread() { public void run() { while (true) { eat(); play(); sleep(); //如果用这个代替下面的语句,会如何? //T.this.sleep(); } } }.start(); } public static void main(String[] args){ new T("Fido", "beef", "Woof").live(); }}
------解决方案--------------------
------解决方案--------------------
Fido: Mmmmm, beef
Fido: Woof Woof
Fido: Zzzzzzz…
以上都说得很清楚了
------解决方案--------------------
------解决方案--------------------
------解决方案--------------------