package cn.zhang.java;
/*水池的容量是固定的500L,一边为进水口,一边为出水口.
要求,进水与放水不能同时进行.水池一旦满了不能继续注水,一旦放空了,不可以继续放水. 进水的速度5L/s , 放水的速度2L/s
*/
class Poool{
static int volome =0;
boolean flag=true;
}
// 定义进水口
class In extends Thread{
Poool p;
int inwater;
public In(Poool p){
this.p=p;
}
@Override
public void run() {
while(true){
synchronized (p) {
if(p.flag==true||inwater<500){
System.out.println("加水中,加了:"+inwater);
p.flag=false;
inwater+=5;
p.notify();
}else {
try {
p.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
// 定义出水口
class Out extends Thread{
Poool p;
int outwater;
public Out(Poool p){
this.p=p;
}
@Override
public void run() {
while(true){
synchronized (p) {
if(p.flag==false){
if(p.flag==false||outwater>0){
System.out.println("放水中,放了:"+outwater);
p.flag=true;
outwater-=2;
p.notify();
}else{
try {
p.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
}
public class Do1 {
public static void main(String[] args) {
Poool p=new Poool();
In in =new In(p);
Out out = new Out(p);
in.start();
out.start();
}
}
输出:
水中,加了:151225
放水中,放了:-60294
加水中,加了:151230
放水中,放了:-60296
加水中,加了:151235
放水中,放了:-60298
加水中,加了:151240
。。。。。
感觉往两个方向走了,写了一下午,一直没弄明白、
不是不能同时进水和出水吗,两个线程是同时运行的
inwater 和outwater,你这写的,貌似没关系吧!独立的两个变量!所以一直往两个方向走啊!
另外:
if(p.flag==true||inwater if(p.flag==false||outwater>0){ //这行应该改成if(p.flag==false||outwater>0){
要不你这代码没意义啊!