码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-12-05 19:51:08      阅读:363      评论:0      收藏:0      [点我收藏+]

标签:应用   his   pool   override   bsp   demo   速度   new   固定   

package demo2;

 class Pooll {

    /**1:有一个水池,水池的容量是固定 的500L,一边为进水口,一边为出水口.
     * 要求,进水与放水不能同时进行.
     水池一旦满了不能继续注水,一旦放空了,不可以继续放水. 进水的速度5L/s ,
       放水的速度2L/s  
     * @param args
     */

     int capacity = 0;    
 }
        
 
 //进水
class Feedwater  extends Thread{

     Pooll p;
 
  public Feedwater (Pooll p) {
      
         this.p = p;
   }
     
   @Override
   public void run() {
       
       while(true){
           
           synchronized (p) { // 任意类型的对象  ,锁对象应该是同一个对象  
               
              if((p.capacity + 5) <= 500){
                    
                  System.out.println("进水中,水池容量为:"+(p.capacity + 5));
                     
                  p.capacity += 5;
                  p.notify();
               }else{
                   
                  System.out.println("水池水满了");
                  try {
                         p.wait();
                         
                        } catch (InterruptedException e) {
                            
                        e.printStackTrace();
                       }
                }
            }
          }
       }
 }
 


 // 出水
class Outwater extends Thread{
 
     Pooll p;
 
    public Outwater(Pooll p) {
        
       this.p = p;
     }
    
 
public void run() {
        
      while(true){
          
        synchronized (p) { // 任意类型的对象  ,锁对象应该是同一个对象   
            
         if((p.capacity - 2) >= 0){
                  
             System.out.println("水池出水中,水池容量为:"+(p.capacity - 2));
                 
            p.capacity -= 2;
            p.notify();
            
        }else{    
                 
             System.out.println("水池没水了");
             try {
                
                  p.wait();
                  
                 } catch (InterruptedException e) {
                    
                 e.printStackTrace();
                 }
             }
         }
      }
    }
 }
 
 
 
 public class Pool {

    public static void main(String[] args) {
        
        Pooll p = new Pooll();
        
        Feedwater  in = new Feedwater (p);
        
        Outwater out = new Outwater (p);
        
              in.start();
           out.start();
    }
 }





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

标签:应用   his   pool   override   bsp   demo   速度   new   固定   

原文地址:http://www.cnblogs.com/yuguangblog/p/6134784.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!