创建一个容量为 100 升的水池,在水池设置 3 个出水口,A 出水口每秒排出 1
升水,B 出水口一秒排出 2 升水,C 出口一秒排出 3 升水,每一次只能随机打开
一个出口排水,使用线程模拟 3 个出水口随机排水的场景,并计算出多少秒后水
池的水被排光。
public class exercise {
volatile int capacity = 100;
static int count=0;
public synchronized boolean drainage(int value) {
if (capacity == 0) {
System.out.println("排完水共消耗时间:"+count+"s");
return false;
} else {
capacity -= value;
capacity = capacity < 0 ? 0 : capacity;
System.out.println("水池还剩" + capacity + "升水");
count++;
return true;
}
}
class Outfall extends Thread {
String name;
int value;
public Outfall(String name, int value) {
this.name = name;
this.value = value;
}
public void run() {
while (drainage(value)) {
System.out.println(name + "排水口完成排水");
}
}
}
public void startThread() {
Thread a = new Outfall("A", 1);
Thread b = new Outfall("B", 2);
Thread c = new Outfall("C", 3);
a.start();
b.start();
c.start();
}
public static void main(String[] args) {
exercise p = new exercise();
p.startThread();
}
}