完全解耦:
public class Application{
public static void main(String Args[]){
House house=new House();
house.setWater(10);
Thread dog,cat;
dog=new Thread(house);
cat=new Thread(house);
dog.setName("狗");
cat.setName("猫");
dog.start();
cat.start();
}
}
class House implements Runnable{
int waterAmount;
public void setWater(int w){
waterAmount=w;
}
public void run(){
while(true){
String name=Thread.currentThread().getName();
if(name.equals("狗")){
System.out.print(name+"喝水");
waterAmount=(waterAmount>=2?waterAmount-2:0);
}
else if(name.equals("猫")){
System.out.print(name+"喝水");
waterAmount=(waterAmount>=1?waterAmount-1:0);
}
System.out.println("剩"+waterAmount);
try{
Thread.sleep(2000);
}
catch(InterruptedException e){}
if(waterAmount<=0){
return;//为什么执行return后程序会停止?
}
}
}
}
弱耦合关系:
public class Application{
public static void main(String Args[]){
House house=new House();
house.setWater(10);
house.dog.start();
house.cat.start();
}
}
class House implements Runnable{
int waterAmount;
Thread dog,cat;
House(){
dog=new Thread(this);
cat=new Thread(this);
}
public void setWater(int w){
waterAmount=w;
}
public void run(){
while(true){
Thread t=Thread.currentThread();
if(t==dog){
System.out.print("狗喝水");
waterAmount=(waterAmount>=2?waterAmount-2:0);
}
else if(t==cat){
System.out.print("猫喝水");
waterAmount=(waterAmount>=1?waterAmount-1:0);
}
System.out.println("剩"+waterAmount);
try{
Thread.sleep(2000);
}
catch(InterruptedException e){}
if(waterAmount<=0){
return;
}
}
}
}
从结果看,两者似乎都是弱耦合,但是第一种书上写的是完全解耦。