Use of communication between the threads to achieve the water drainage tank

Source: Internet
Author: User

Business requirements, water speed 5l/s, discharge speed 2l/s, water can not be added, water can not be added, pool capacity 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;//constructor public waterin (pool pool) {this.pool = Pool;}  @Overridepublic 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 plus water to:" +pool.volume);  }} else{System.out.println ("The Water is full" +pool.volume);  Pool.flag = true;  Pool.notify (); }}else{try {pool.wait ();} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}} }class Waterout extends Thread{pool pool = new Pool (); int temp;//constructor public waterout (pool pool) {This.pool = pool;} @Overridepublic void Run () {while (true) {synchronized (pool) {///identifies if (Pool.flag) {if (pool.volume>0) {Pool.volume-=pool.wateroutspeed;    if (temp++%20 = = 0) System.out.println ("Water has been put into" +pool.volume);  }else{System.out.println ("The water has been put out" +pool.volume);  Pool.flag = false;  Pool.notify ();  }}else{try {pool.wait ()} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} }  }  }}

  

Pool Pool =new pool (); Waterin in =new waterin (pool); Waterout out = new Waterout (pool); In.start (); Out.start ();

  

Use of communication between the threads to achieve the water drainage tank

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.