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

java 简单的进水放水

时间:2016-12-03 09:56:04      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:auto   nbsp   while   print   gen   zed   interrupt   ace   ati   

class Shui implements Runnable{
     int a=0;
    @Override
    
    public void run() {
        synchronized (this) {
        while (true) {
        String str= Thread.currentThread().getName();
                
                if (str.equals("进水")) {
                    if (a>496) {
                        this.notify();
                        try {
                            this.wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            
                            e.printStackTrace();
                        }
                        
                        
                    }
                    a+=5;
                    System.out.println("每秒进水5升水池还有"+a);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    
                }
                
                if (str.equals("放水")) {
                    if (a<2) {
                        this.notify();
                        try {
                            this.wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            
                            e.printStackTrace();
                        }
                        
                        
                    }
                    a-=2;
                    System.out.println("每秒放水2升水池还有"+a);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                
                }
                
                
                
            }
        }
        
    }
    
}
public class work1 {
    
    
    public static void main(String[] args) {
        Shui sss=new Shui();
          Thread t = new Thread(sss,"进水");
          Thread t1 = new Thread(sss,"放水");
          t.start();
          t1.start();
        
    }

}

java 简单的进水放水

标签:auto   nbsp   while   print   gen   zed   interrupt   ace   ati   

原文地址:http://www.cnblogs.com/zzzhangzheng/p/6127998.html

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