首页 > 代码库 > 利用线程间的通讯实现的水池加水放水

利用线程间的通讯实现的水池加水放水

业务需求,加水速度5L/s,放水速度2L/s,加水时不能放水,放水时不能加水,水池容量500L

class Pool{
	
	int volume = 0;
	int maxVolume = 500;
	int waterInSpeed = 5;
	int waterOutSpeed = 2;
	boolean flag = false;
	
}

class WaterIn extends Thread{
	
	Pool pool = new Pool();
	
	int temp = 0;
	//构造器
	public WaterIn(Pool pool) {
		this.pool = pool;
	}
	@Override
	public void run(){
		while(true){
			synchronized (pool) {
			  if(!pool.flag){
				  try {
					  Thread.sleep(10);
				  } catch (InterruptedException e) {
					  // TODO Auto-generated catch block
					  e.printStackTrace();
				  }
				  if(pool.volume < pool.maxVolume){
					  pool.volume += pool.waterInSpeed;
					  if(temp++%10 == 0){
						  System.out.println("水池加水到:"+pool.volume);
						  
					  }
				  }
				  else{
					  System.out.println("水已经满了"+pool.volume);
					  pool.flag = true;
					  pool.notify();
				  }
			    }else{
					try {
						pool.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}
}
class WaterOut extends Thread{
	
	Pool pool = new Pool();
	int temp;
	//构造器
	public WaterOut(Pool pool) {
		this.pool = pool;
	}
	@Override
	public void run(){
		  while(true){
			  synchronized(pool){
				  //进行标识判断
				  if(pool.flag){
					  if(pool.volume>0){
						  pool.volume -=pool.waterOutSpeed;
						  if(temp++%20 == 0)
							  System.out.println("水已经放到"+pool.volume);
						  
					  }else{
						  System.out.println("水已经放完了"+pool.volume);
						  pool.flag = false;
						  pool.notify();
					  }
				  }else{
					  try {
						pool.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				  }
			  }
		  }
	}

  

Pool pool =new Pool();
		WaterIn in =new WaterIn(pool);
		WaterOut out = new WaterOut(pool);
		in.start();
		out.start();

  

利用线程间的通讯实现的水池加水放水