java_xiaodi 2016-06-16 11:04 采纳率: 80%
浏览 1323

小白最近在学到java的多线程,遇到一个问题,求大神

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();
}

}

  • 写回答

3条回答 默认 最新

  • java_xiaodi 2016-06-16 11:08
    关注

    输出:
    水中,加了:151225
    放水中,放了:-60294
    加水中,加了:151230
    放水中,放了:-60296
    加水中,加了:151235
    放水中,放了:-60298
    加水中,加了:151240
    。。。。。
    感觉往两个方向走了,写了一下午,一直没弄明白、

    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献