水池进水与出水问题 – 线程 java
package com.xzy;
/**
* 有一个水池,水池的容量是固定 的500L,一边为进水口,一边为出水口.
* 要求,进水与放水不能同时进行. 水池一旦满了不能继续注水,一旦放空了,不可以继续放水.
* 进水的速度5L/s , 放水的速度2L/s
* @author 娟娟
*
*/
//水池
class Pool{
int capacity = 0;//水池的容量
}
//进水口
class inWater extends Thread{
Pool p;
public inWater(Pool p) {
this.p = p;
}
@Override
public void run() {
while(true) {
synchronized (p) {
if((p.capacity + 5) <= 50) {
System.out.println("进水中,水池的容量为:" + (p.capacity + 5));
p.capacity += 5;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
p.notify();
}else {
System.out.println("水池水满了...");
try {
p.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
//出水口
class outWater extends Thread{
Pool p;
public outWater(Pool p) {
this.p = p;
}
@Override
public void run() {
while(true) {
synchronized (p) {
if((p.capacity - 2) >= 0) {
System.out.println("出水中,水池的容量为" + (p.capacity - 2));
p.capacity -= 2;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
p.notify();
}else {
System.out.println("水池没水了...");
try {
p.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public class Main {
public static void main(String[] args) {
Pool p = new Pool();
inWater iw = new inWater(p);
outWater ow = new outWater(p);
iw.start();
ow.start();
}
}