首页 > 代码库 > 利用线程间的通讯实现的水池加水放水
利用线程间的通讯实现的水池加水放水
业务需求,加水速度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();
利用线程间的通讯实现的水池加水放水
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。