Threads in Java to solve incoming and outgoing water problems

Source: Internet
Author: User

Inlet class inflow implements runnable{//water object water wat;public inflow (water w) {This.wat = W;} @Overridepublic void Run () {//Water inlet while (true) {synchronized (WAT) {while (true) {if (Wat.count >=) {wat.notify (); try {wat.wait ();} catch (Interruptedexception e) {e.printstacktrace ();}} try {//Sleep thread thread.sleep (+),} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} wat.count++; System.out.println ("Now in water, water:" + Wat.count);}}}} Effluent class outflow implements Runnable{water Wat;public outflow (water w) {This.wat = W;} @Overridepublic void Run () {//Effluent while (true) {//Line lock synchronized (WAT) {while (true) {if (wat.count <= 0) {wat.notify (); try {wat.wait ();} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} try {thread.sleep;} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} wat.count--; System.out.println ("Is now in water, the remaining amount is:" + Wat.count);}}}} Class Water{int count = 50;} public class Demo5{public static void main (string[] args) {//Create water object water water = new water ();//Water object inflow in = new inflow (water);//Drain Object Outflo W out = new outflow (water),//thread thread = new thread (in); Thread the = new thread (out);//Open thread Thread.Start (); The.start ();}}

  

Threads in Java to solve incoming and outgoing water problems

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.