] 创建一个容量为100升的水池,在水池上设置3个出水口,A出水口每秒排出1升水,B出水口每秒排出2升水,C出水口每秒排出3升水 用继承Thread类的方式设计排水口线程类Outfall,创建成员变量water表示水池剩余水量,成员变量speed表示排水口的排水速度,创建构造方法初始化线程类名称和排水速度,重写run()方法实现排水口的排水功能,要求每次排水后在控制台打印剩余的水量 创建测试类PoolDemo,在main()方法中模拟三个排水口同时排水的场景,至少输出5种排水结果
时间: 2024-01-03 16:06:02 浏览: 36
下面是实现的代码:
```java
class Outfall extends Thread {
private int water; // 水池剩余水量
private int speed; // 排水口的排水速度
public Outfall(String name, int speed, int water) {
super(name);
this.speed = speed;
this.water = water;
}
public void run() {
while (water > 0) {
water -= speed;
if (water < 0) {
water = 0;
}
System.out.println(Thread.currentThread().getName() + " 排水后,水池中还剩余 " + water + " 升水");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class PoolDemo {
public static void main(String[] args) {
Outfall A = new Outfall("A出水口", 1, 100);
Outfall B = new Outfall("B出水口", 2, 100);
Outfall C = new Outfall("C出水口", 3, 100);
A.start();
B.start();
C.start();
}
}
```
输出结果可能如下:
```
B出水口 排水后,水池中还剩余 98 升水
A出水口 排水后,水池中还剩余 99 升水
C出水口 排水后,水池中还剩余 97 升水
B出水口 排水后,水池中还剩余 96 升水
A出水口 排水后,水池中还剩余 98 升水
C出水口 排水后,水池中还剩余 94 升水
B出水口 排水后,水池中还剩余 92 升水
A出水口 排水后,水池中还剩余 97 升水
C出水口 排水后,水池中还剩余 91 升水
B出水口 排水后,水池中还剩余 88 升水
```
需要注意的是,由于线程是并发执行的,输出结果可能会有一定的不确定性。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)