class Water{ //水塘类 static Object water=new Object(); static int total=6; //假设水塘总共可以含水量为6 static int mqsl=3; //假设水塘中拥有含水量为3 static int ps=0; //假设水塘目前含水量为0 } class ThreadA extends Thread{ //排水类 void pswork(){ synchronized(Water.water){ System.out.println("水塘中是否没有水: "+isEmpty()); if(isEmpty()){ try{ Water.water.wait(); } catch(InterruptedException e){ e.printStackTrace(); } } else{ Water.ps++; System.out.println("水塘目前排水水量 "+Water.ps); } } } public void run(){ while(Water.mqsl<Water.total){ if(isEmpty()) System.out.println("水塘目前没有水,排水线程被挂起"); System.out.println("排水工作开始"); pswork(); try{ sleep(1000); } catch(InterruptedException e){ e.printStackTrace(); } } } public boolean isEmpty(){ return Water.mqsl==Water.ps?true:false; } } class ThreadB extends Thread{ //进水类 void jswork() { synchronized(Water.water){ Water.mqsl++; Water.water.notify(); System.out.println("水塘目前进水量为 "+Water.mqsl); } } public void run(){ while(Water.mqsl<Water.total){ System.out.println("进水工作开始"); jswork(); try{ sleep(3000); } catch(InterruptedException e){ e.printStackTrace(); } } } } public class Tongxin { public static void main(String[] args) { // TODO Auto-generated method stub ThreadA threadA=new ThreadA(); ThreadB threadB=new ThreadB(); threadB.start(); threadA.start(); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。