Java multithreaded simulation traffic light case

Source: Internet
Author: User

Code Lighter.java:

1  PackagePack1;2 /**3 * Lamp Thread4  * @authorAdministrator5  *6  */7  Public classLighterextendsthread{8 //represents the current state of the lamp (only the red and green states are considered here)9  PublicString State;Ten  Public voidrun () { One      while(true){ A         Try { -             //The initial state is set to red, and the red light is always 10s -state = "Red"; theSystem.out.println ("Lighter: Now it's a red light, stationary vehicle traffic"); -Thread.Sleep (10*1000); -             //10s rear light turn green, set green time bit 5 seconds -state = "Green"; +System.out.println ("Lighter: Now the green light, the vehicle can pass." "); -Lighter.sleep (5*1000); +}Catch(interruptedexception e) { ASystem.out.println ("Error:" +e); at         } -     } - } -}

Code Car.java

 PackagePack1;/*** Vehicle Thread *@authorAdministrator **/ Public classCarextendsthread{string name="";//lights as private variables, the vehicle according to the status of the lamp to decide whether to stopPrivatelighter lighter; PublicCar (String name,lighter l) { This. name=name;  This. lighter=l;} Public voidrun () {if(Lighter.state.equals ("Red") {System.out.println ( This. name+ ": Waiting in"); }Else{System.out.println ( This. name+ ": Passed the traffic light"); }}}

Test Code Rglighttest.java

1  PackagePack1;2 /**3 * Traffic light test code4  * @authorAdministrator5  *6  */7  Public classRglighttest {8  Public Static voidMain (string[] args)throwsinterruptedexception {9Lighter l=Newlighter ();Ten         //traffic lights start running One L.start (); A         //generate 20 vehicles, followed by a traffic light -      for(inti=0;i<20;i++){ -Car c=NewCar ("Car" +i+1, L); the                 //current vehicle sleep 1s -C.sleep (1000); - C.start (); -     } + } -}

Java multithreaded simulation traffic light case

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.