Java Learning ———— Thread Direct communication

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.