Traffic light Management System

Source: Internet
Author: User

I. Requirements

  • The traffic light management system logic at the intersection is simulated. The specific requirements are as follows:

Asynchronously and randomly generate vehicles traveling along each route.

For example:

Vehicles from south to north-direct vehicles

Vehicles going from West to south-turn right

Vehicles from the east to the south-turn vehicles

......

  • Ignore the yellow light, only the red light and the green light are considered.
  • A left-turn vehicle control signal light should be considered, and a right-turn vehicle is not controlled by the signal light.
  • The specific traffic signal control logic is the same as that of common traffic signals in real life.

Note: vehicles in the North-South direction and vehicles in the east-west direction are allowed to interchangeably. vehicles in the same direction should be allowed to go directly and then turn left.

  • The intersection time for each vehicle to pass is 1 second (Prompt: simulation can be performed by thread sleep ).
  • You can set the random generation interval and traffic light switching interval.
  • GUI is not required. You only need to implement the system logic. You can use the LOG method to display the program running results.
2. Object-Oriented Analysis and Design
  1. Multiple vehicles will appear on each route. New vehicles should be randomly added on the route, and a car should be reduced every second during the light-green period.
  2. Design a road class to represent a route. Each road object represents a route. There are 12 routes in total, that is, a total of 12 road instance objects will be generated in the system.
  3. A new vehicle is randomly added to each route and saved in a collection.
  4. Every second, each route checks whether the lights that control the current route are green. If yes, the first car in the car's set stored in the current route is removed, indicating that the car passes through the intersection.
  5. Every second of each route checks whether the light that controls the current route is green. When a light changes from green to red, the light in the next direction should be green.
  6. Design a lamp class to represent a traffic light. Each traffic light maintains a state: Bright (green) or not bright (RED). Each traffic light must have a method of changing from Bright to black, and can return their own bright black state.
  7. There are 12 routes in total, so a total of 12 traffic lights are generated in the system. The route of the right turn is not controlled by the light, but in order to let the program adopt a unified processing method, it is assumed that there are four right turn lights, but these lights are always on, that is, it never changes.
  8. In addition to the lights of the other eight routes in the right turn direction, they are paired and can be classified into four groups. Therefore, during programming, as long as one lamp is taken from each of the four groups, the four lights are turned on in round-robin mode, and the lights corresponding to the four lights change with each other, therefore, there must be a variable in the lamp class to remember the lights in the opposite direction. In the method of brightening and blackening a lamp object, the lights in the corresponding direction are also brightened and dimmed. When the light turns black, it is followed by the light of the next light, and a variable is used in the lamp class to remember its next light.
  9. No matter where the program gets the lights in a certain direction, each time it gets the same instance object, it is very convenient for the lamp class to use enumeration, there are always only instance objects that represent the lights in 12 directions.
  10. Design a lampcontroller class, which regularly turns the current green light red.
Iii. Detailed Design of Road class Writing
  • Each road object has a name member variable to represent the direction, and a vehicles member variable to represent the vehicle set in the direction.
  • In the road object constructor, enable a thread to add a vehicle to the vehicles set at every random time (represented by a string in the form of "route name _ id ).
  • Enable a timer in the construction method of the road object, and check whether the light in the direction is green every second. If yes, print the vehicle set and remove the first car from the set.
Compiling the lamp class
  • There are 12 lights in the system. In other places of the program, the corresponding lamp instance objects can be obtained based on the lamp name. Based on these factors, it is easier to define the lamp class in the enumeration form in Java 5.
  • The bright black state in each lamp object is represented by the lighted variable. The lamp objects in the s2n, s2w, e2w, and e2n directions are selected for round-robin and brightening, the lamp object also has an oppositelampname variable to indicate the lights in the opposite direction. Then, a nextlampname variable is used to indicate the next bright light after the light turns on. The three variables are assigned values in the form of constructor. Because enumeration elements must be referenced after definition, they cannot be referenced by each other in constructor, the lights in the opposite direction and the next direction are represented in strings.
  • The following methods are added to brighten and blacklist a lamp: Light and blackout. For lamp objects in four directions: s2n, s2w, e2w, and e2n, inside the two methods, the light in the opposite direction should be turned on and black, and the blackout method should also turn on the next light.
  • In addition to lamp objects in the s2n, s2w, e2w, and e2n directions, the nextlampname and oppositelampname attributes of lamp objects in other directions are set to null, the nextlampname and oppositelampname attributes of lamp objects in the s2n, s2w, e2w, and e2n directions must be set to null to prevent light and blackout from entering an endless loop.
Write the lampcontroller class
  • The entire system can only have one set of traffic light control systems. Therefore, it is best to design the lampcontroller class into a singleton.
  • Set the first green light in the lampcontroller constructor.
  • In the start method of the lampcontroller object, the current light turns green, and then a timer is started. The current light turns red every 10 seconds and the next light turns green.
Writing mainclass
  • Use the for loop to create Objects representing 12 routes.
  • Then obtain the lampcontroller object and call its start method.
Iv. Encoding
Import Java. util. arraylist; import Java. util. list; import Java. util. random; import Java. util. concurrent. executorservice; import Java. util. concurrent. executors; import Java. util. concurrent. scheduledexecutorservice; import Java. util. concurrent. timeunit;/*** each road object represents a route. There are 12 routes in total, that is, a total of 12 road instance objects are generated in the system. * A new vehicle is randomly added to each route and added to a collection for saving. * Every second of each route, the system checks whether the lights on the current route are green. If yes, the first car in the set of vehicles stored in the current route is removed, indicating that the car passes through the intersection. * @ Author Zhang Xiaoxiang www.it315.org **/public class road {private list <string> vechicles = new arraylist <string> (); Private string name = NULL; public road (string name) {This. name = Name; // simulate the process of random vehicles on the road executorservice pool = executors.newsinglethreadexecutor(registry.pool.exe cute (New runnable () {public void run () {for (INT I = 1; I <1000; I ++) {try {thread. sleep (new random (). nextint (10) + 1) * 1000);} catch (interruptedexc Eption e) {e. printstacktrace ();} vechicles. add (Road. this. name + "_" + I) ;}}); // check whether the corresponding lamp is green every second. If yes, release a car scheduledexecutorservice timer = executors. newscheduledthreadpool (1); timer. scheduleatfixedrate (New runnable () {public void run () {If (vechicles. size ()> 0) {Boolean lighted = lamp. valueof (Road. this. name ). islighted (); If (lighted) {system. out. println (vechicles. remove (0) + "is traversing! ") ;}}}, 1, 1, timeunit. Seconds );}}

/*** Each lamp element represents a lamp in one direction, with 12 directions in total and 12 lamp elements in all directions. * There are lights in the following directions, each of which forms a group, and a group of lights turn green or red at the same time. Therefore, * the program code only needs to control one of the lights in each group: * s2n, n2s * s2w, n2e * e2w, w2e * e2s, w2n * s2e, n2w * e2n, w2s * The lights on the last two lines are virtual, since the south to the east and the west to the north, and their corresponding directions are not controlled by traffic lights, * We can assume that they are always green lights. * @ Author Zhang Xiaoxiang www.it315.org ** // **/Public Enum lamp {/* Each enumeration element represents a direction control lamp */s2n ("N2s", "s2w ", false), s2w ("n2e", "e2w", false), e2w ("w2e", "e2s", false), e2s ("w2n", "s2n ", false),/* the following elements indicate the lights in the opposite direction of the above elements. Their "Opposite Direction lights" and "next lights" should be ignored! */N2s (null, null, false), n2e (null, null, false), w2e (null, null, false), w2n (null, null, false ), /* right turns from the south to the east and from the west to the north are not controlled by traffic lights. Therefore, we can assume that they are always green lights */s2e (null, null, true), e2n (null, null, true), n2w (null, null, true), w2s (null, null, true); Private lamp (string opposite, string next, Boolean lighted) {This. opposite = opposite; this. next = next; this. lighted = lighted;}/* whether the current light is green */private Boolean lighted;/* The direction corresponding to the green light at the same time */private string OPP Osite;/* The next green light when the current light turns red */private string next; Public Boolean islighted () {return lighted;}/*** when a light turns green, the light in the corresponding direction must also turn green */Public void light () {This. lighted = true; If (opposite! = NULL) {lamp. valueof (opposite ). light ();} system. out. println (name () + "lamp is green, there should be a total of 6 directions to see the car pass! ");}/*** When a light turns red, the light turns red in the corresponding direction, and the lights in the next direction need to turn green * @ return next the lights to turn green */public lamp blackout () {This. lighted = false; If (opposite! = NULL) {lamp. valueof (opposite). blackout ();} lamp nextlamp = NULL; If (next! = NULL) {nextlamp = lamp. valueof (next); system. out. println ("green light from" + name () + "--------> switch to" + next); nextlamp. light () ;}return nextlamp ;}}

Import Java. util. concurrent. executors; import Java. util. concurrent. scheduledexecutorservice; import Java. util. concurrent. timeunit; public class lampcontroller {private lamp currentlamp; Public lampcontroller () {// green the lampcontroller from south to north at the beginning; currentlamp = lamp. s2n; currentlamp. light ();/* change the current green light to a red light every 10 seconds and change the light in the next direction to green */scheduledexecutorservice timer = executors. newscheduledthreadpool (1); timer. scheduleatfixedrate (New runnable () {public void run () {system. out. println ("come on"); currentlamp = currentlamp. blackout () ;}}, 10, 10, timeunit. seconds );}}
Public class mainclass {/*** @ Param ARGs */public static void main (string [] ARGs) {/* generate 12 directions */string [] directions = new string [] {"s2n", "s2w", "e2w", "e2s ", "N2s", "n2e", "w2e", "w2n", "s2e", "e2n", "n2w", "w2s"}; For (INT I = 0; I <directions. length; I ++) {New Road (directions [I]);}/* generate the entire traffic light system */New lampcontroller ();}}

V. Summary

Before watching the video, I saw the demand and felt like I could not help. After watching the video, I think that in Object-Oriented Programming, analysis and design are very important. Before I really understand the needs, I can draw pictures for analysis. This video provides a better understanding of object-oriented encapsulation, multithreading, and enumeration.

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.