需求:
有一个水池100L,有出水口和入水口,出水口和入水口不能同时打开,入水口每次注入5L水,出水口每次出4L水,如果池子注满水,或者池子中没有水就停止。
使用继承Thread类的方式编写出水口,使用实现Runnable方式编写入水口,运行结果。
package pool;
/**
*
* 出水口outfall 入水口inflow 水池pool
*
*/
class Waterpool{
public static int pool =5;
static boolean isTrue = true;
}
class Outfall extends Thread {
Waterpool w;
public Outfall(Waterpool w) {
super();
this.w =w;
}
@Override
public void run() {
while (Waterpool.isTrue) {
synchronized (w) {
if(Waterpool.pool>995 && Waterpool.pool<1000){
System.out.println("加水"+(1000-Waterpool.pool)+"L后水满了");
Waterpool.pool=1000;
Waterpool.isTrue= false;
}else if (Waterpool.pool < 1000 && Waterpool.pool>0) {
Waterpool.pool=Waterpool.pool+5;
System.out.println("加水5L当前水量后"+Waterpool.pool);
}else {
System.out.println("不能加水了");
Waterpool.isTrue= false;
}
}
}
}
}
class Inflow implements Runnable {
Waterpool w;
public Inflow(Waterpool w) {
this.w =w;
}
@Override
public void run() {
while (Waterpool.isTrue) {
synchronized (w) {
if(Waterpool.pool>0 && Waterpool.pool<4) {
System.out.println("出水"+Waterpool.pool+"L后没水了");
Waterpool.pool=0;
Waterpool.isTrue= false;
}else if (Waterpool.pool>0 && Waterpool.pool<1000) {
Waterpool.pool = Waterpool.pool-4;
System.out.println("出水4L后当前水量"+Waterpool.pool);
}else {
System.out.println("不能放水了");
Waterpool.isTrue= false;
}
}
}
}
}
public class Homework {
public static void main(String[] args) {
Waterpool w =new Waterpool();
Outfall outfall =new Outfall(w);
Inflow inflow = new Inflow(w);
outfall.start();
Thread in = new Thread(inflow);
in.start();
}
}