Class water{//Reservoir type Static Object Water=new object (); static int total=6; Suppose that the reservoir can have a total water content of 6static int mqsl=3; Suppose the reservoir has a water content of 3static int ps=0; Assuming the current water content of the reservoir is 0}class Threada extends thread{//drainage void pswork () {synchronized (water.water) {System.out.println (" Whether there is no water in the pond: "+isempty ())", if (IsEmpty ()) {try{water.water.wait ();} catch (Interruptedexception e) {e.printstacktrace ();}} else{water.ps++; System.out.println ("The current water drainage of the pond" +water.ps);}}} public void Run () {while (water.mqsl<water.total) {if (IsEmpty ()) System.out.println ("The pond currently has no water, the drain thread is suspended"); System.out.println ("Commencement of drainage work");p swork (); try{sleep (1000);} catch (Interruptedexception e) {e.printstacktrace ();}}} public Boolean isEmpty () {return water.mqsl==water.ps?true:false;}} Class Threadb extends thread{//water type void jswork () {synchronized (water.water) {water.mqsl++; Water.water.notify (); System.out.println ("The current water intake of the pond is" +WATER.MQSL);}} public void Run () {while (water.mqsl<water.total) {System.out.println ("inlet work Start"); Jswork (); Try{sleep (3000);} catch (Interruptedexception e) {E.printstackTrace ();}}} public class Tongxin {public static void main (string[] args) {//TODO auto-generated method Stubthreada threada=new Thread A (); THREADB threadb=new threadb (); Threadb.start (); Threada.start ();}}
Java Learning ———— Thread Direct communication