package demo2;
class Pooll {
/**1:有一个水池,水池的容量是固定 的500L,一边为进水口,一边为出水口.
* 要求,进水与放水不能同时进行.
水池一旦满了不能继续注水,一旦放空了,不可以继续放水. 进水的速度5L/s ,
放水的速度2L/s
* @param args
*/
int capacity = 0;
}
//进水
class Feedwater extends Thread{
Pooll p;
public Feedwater (Pooll p) {
this.p = p;
}
@Override
public void run() {
while(true){
synchronized (p) { // 任意类型的对象 ,锁对象应该是同一个对象
if((p.capacity + 5) <= 500){
System.out.println("进水中,水池容量为:"+(p.capacity + 5));
p.capacity += 5;
p.notify();
}else{
System.out.println("水池水满了");
try {
p.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
// 出水
class Outwater extends Thread{
Pooll p;
public Outwater(Pooll p) {
this.p = p;
}
public void run() {
while(true){
synchronized (p) { // 任意类型的对象 ,锁对象应该是同一个对象
if((p.capacity - 2) >= 0){
System.out.println("水池出水中,水池容量为:"+(p.capacity - 2));
p.capacity -= 2;
p.notify();
}else{
System.out.println("水池没水了");
try {
p.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public class Pool {
public static void main(String[] args) {
Pooll p = new Pooll();
Feedwater in = new Feedwater (p);
Outwater out = new Outwater (p);
in.start();
out.start();
}
}