水池进水与出水问题 -- 线程 java

水池进水与出水问题 – 线程 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();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值