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

Posted 人生第一步

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了利用线程间的通讯实现的水池加水放水相关的知识,希望对你有一定的参考价值。

业务需求,加水速度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();

  

以上是关于利用线程间的通讯实现的水池加水放水的主要内容,如果未能解决你的问题,请参考以下文章

水池进水与放水问题(多线程应用)

利用QSystemSemaphore和QSharedMemory实现进程间通讯

java

同一进程间的线程共享资源

利用多线程实现Future模式

python 进程