![]() |
#2
q4522273612015-08-27 16:37
|

//有一个水池,水池的容量是固定 的500L,一边为进水口,一边为出水口.要求,进水与放水不能同时进行.
//水池一旦满了不能继续注水,一旦放空了,不可以继续放水. 进水的速度5L/s , 放水的速度2L/s
package 线程;
class 作业{
public static void main(String[] args){
pool p = new pool();
out o = new out(p);
in i = new in(p) ;
o.start();
i.start();
}
}
class pool{
int count =500 ;
boolean full=false;
}
//放水 判断有水不 有就放 没就进水
class out extends Thread{
pool p;
int rate = 2; //速率
int time = 1; //时间
int total= 1; //总量
public out(pool p){
this.p=p;
}
public void run(){
synchronized(p){
if(p.full==true){ //如果水满了就开始放水
while(total<p.count){ //如果放出的水总量大于500就停止放水
System.out.println("放水中。。。已放 "+total);
time++;
total=rate * time;
}
p.full=false; //水空了
p.notify(); //唤醒进水线程
}else{
try{
p.wait(); //进入等待状态
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
}
//进水 判断是否有水 有就放水 没就进水
class in extends Thread{
pool p;
int rate = 5;
int time = 1;
int total= 1;
public in(pool p){
this.p=p;
}
public void run(){
synchronized(p){
if(p.full==false){ //如果水空了就开始进水
while(total<p.count){ //如果进入的水总量大于500就停止进水
System.out.println("进水中。。。已进水 "+total);
time++;
total=time*rate;
}
p.notify(); //唤醒放水线程
p.full=true; //水满了
}else{
try{
p.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
}
//水池一旦满了不能继续注水,一旦放空了,不可以继续放水. 进水的速度5L/s , 放水的速度2L/s
package 线程;
class 作业{
public static void main(String[] args){
pool p = new pool();
out o = new out(p);
in i = new in(p) ;
o.start();
i.start();
}
}
class pool{
int count =500 ;
boolean full=false;
}
//放水 判断有水不 有就放 没就进水
class out extends Thread{
pool p;
int rate = 2; //速率
int time = 1; //时间
int total= 1; //总量
public out(pool p){
this.p=p;
}
public void run(){
synchronized(p){
if(p.full==true){ //如果水满了就开始放水
while(total<p.count){ //如果放出的水总量大于500就停止放水
System.out.println("放水中。。。已放 "+total);
time++;
total=rate * time;
}
p.full=false; //水空了
p.notify(); //唤醒进水线程
}else{
try{
p.wait(); //进入等待状态
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
}
//进水 判断是否有水 有就放水 没就进水
class in extends Thread{
pool p;
int rate = 5;
int time = 1;
int total= 1;
public in(pool p){
this.p=p;
}
public void run(){
synchronized(p){
if(p.full==false){ //如果水空了就开始进水
while(total<p.count){ //如果进入的水总量大于500就停止进水
System.out.println("进水中。。。已进水 "+total);
time++;
total=time*rate;
}
p.notify(); //唤醒放水线程
p.full=true; //水满了
}else{
try{
p.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
}
[ 本帖最后由 q452227361 于 2015-8-27 16:39 编辑 ]