有一水塘,可实现注水和排水操作。当水塘无水时不能对其再进行排水操作,当水塘水满时不能对其再进行注水操作。创建水塘类Pond、注水线程Injection和排水现成Drain,假设注水线程可以在10分钟内将水塘注满水,排水线程可以在10分钟内将水塘的水全排出。试实现水塘的注水和排水过程。用Java多线程实现
时间: 2024-02-12 22:07:10 浏览: 59
好的,我知道了。下面是我的回答:
首先,我们需要定义一个水塘类Pond,它包含一个水量属性和两个方法:注水和排水。注水方法接受一个注水量参数,将水量增加;排水方法将水量减少。由于多线程操作,我们需要使用synchronized关键字来保证线程安全。
```java
public class Pond {
private int waterLevel;
public Pond() {
waterLevel = 0;
}
public synchronized void injectWater(int water) {
while (waterLevel + water > 100) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
waterLevel += water;
System.out.println("注入" + water + "升水,水位为:" + waterLevel + "升");
notifyAll();
}
public synchronized void drainWater(int water) {
while (waterLevel - water < 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
waterLevel -= water;
System.out.println("排出" + water + "升水,水位为:" + waterLevel + "升");
notifyAll();
}
}
```
然后,我们定义一个注水线程Injection和一个排水线程Drain,它们分别调用Pond类的注水和排水方法。
```java
public class Injection implements Runnable {
private Pond pond;
public Injection(Pond pond) {
this.pond = pond;
}
@Override
public void run() {
pond.injectWater(100);
}
}
public class Drain implements Runnable {
private Pond pond;
public Drain(Pond pond) {
this.pond = pond;
}
@Override
public void run() {
pond.drainWater(100);
}
}
```
最后,我们在主方法中创建一个水塘对象和两个线程对象,并启动线程。
```java
public class Main {
public static void main(String[] args) {
Pond pond = new Pond();
Injection injection = new Injection(pond);
Drain drain = new Drain(pond);
new Thread(injection).start();
new Thread(drain).start();
}
}
```
当我们运行程序时,注水线程会将水塘注满,排水线程会将水塘排空。
输出结果如下:
```
注入100升水,水位为:100升
排出100升水,水位为:0升
```