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