zoukankan      html  css  js  c++  java
  • java中用线程解决进出水问题

    //进水
    class Inflow implements Runnable{
    	
    	//水对象
    	Water wat;
    	public Inflow(Water w){
    		this.wat = w;
    	}
    	
    	@Override
    	public void run() {
    		//进水				
    		while (true) {
    			synchronized (wat) {
    				while (true) {
    					if (wat.count >= 50) {
    						wat.notify();
    						try {
    							wat.wait();
    						} catch (InterruptedException e) {
    							e.printStackTrace();
    						}
    					}
    					try {
    						//睡眠线程
    						Thread.sleep(1000);
    					} catch (InterruptedException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
    					wat.count++;
    					System.out.println("现在是在进水,水量为:" + wat.count);
    				}					
    			}
    		
    		}
    	}
    }
    
    
    //出水
    class Outflow implements Runnable{
    	
    	Water wat;
    	public Outflow(Water w){
    		this.wat = w;
    	}
    	
    	@Override
    	public void run() {
    		//出水						
    		while (true) {
    			//线程锁
    			synchronized (wat) {
    				while (true) {
    					if (wat.count <= 0) {
    						wat.notify();
    						try {
    							wat.wait();
    						} catch (InterruptedException e) {
    							// TODO Auto-generated catch block
    							e.printStackTrace();
    						}
    					}
    					try {
    						Thread.sleep(1000);
    					} catch (InterruptedException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
    					wat.count--;
    					System.out.println("现在是在放水,剩余水量为:" + wat.count);	
    				}									
    			}
    		
    		}
    	}
    }
    class Water{
    	
    	int count = 50;
    	
    }
    public class demo5 {
    
    	public static void main(String[] args) {
    		//创建水对象
    		Water Water = new Water();
    		//进水对象
    		Inflow in = new Inflow(Water);
    		//放水对象
    		Outflow out = new Outflow(Water);
    		
    		//
    		Thread thread = new Thread(in);
    		Thread the = new Thread(out);
    		
    		//开启线程
    		thread.start();
    		the.start();
    	}
    
    }
    

      

  • 相关阅读:
    通过另外一个应用程序给多个文本框赋值, 模拟单击事件
    AngularJS
    九章算法
    实现继承
    二分查找
    NET Core依赖注入解读&使用Autofac替代实现
    NET SignalR 与 LayIM2.0
    WebVR
    依赖注入
    如何实现配置与源文件的同步
  • 原文地址:https://www.cnblogs.com/12kk/p/6127952.html
Copyright © 2011-2022 走看看