Typical interview project-traffic light Management System

Source: Internet
Author: User

Project origin: This project was originally a face-to-face question from softlink. It was handed back to the subject for self-completion. After the review is passed, it will pass the interview. Of course, it cannot be used as a face-to-face question now. However, this project is very practical and widely spread on the Internet. From this, we can learn the essence of object-oriented programming, which is even more significant for beginners who have mastered the basics of Java SE. Now let's take a look at this project. Asynchronously and randomly generate vehicles traveling along each route. For example, a vehicle from the South to the North-a vehicle from the east to the south-a right-turn vehicle from the east to the south-a left-turn vehicle... 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: For vehicles in the North-South direction and vehicles in the east-west direction, when waiting for vehicles in the same direction, the vehicle must first be allowed to go directly and then turn left. The time for each vehicle to pass through the intersection is 1 second (note: can be simulated 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. From the project requirements, we can find that there are two main categories: traffic lights and driving vehicles on each route. Route Analysis and time setting: based on the actual situation analysis, we can see that one direction has one route for the other three methods. Since it is a crossroads, the total number of lines is 3x4 = 12. Traffic light rules: the right turn signal lights are evergreen, each car passes through the intersection for 1 second, and there is a car followed by it, here we set the random generation time of a vehicle to 2-10 seconds, set each intersection to go green for 20 seconds, turn left to light for 15 seconds, so we can get the red light for 50 seconds, the left turn red light time is 55 seconds. For example, if the time from the south to the north and from the direct direction to the red light, then at the same time from the south to the west and the turn to the red light time to the turn to the green light time to the turn to the red light, in the same time from the west to the east and direct to the red light time to the green light, the green time to the red light... This reciprocating cycle. So we need a controller to control traffic lights. We use a class to implement this controller during programming. Because the light on a line is exactly the same as the light on the line, and the right green light is always on. According to this phenomenon, we only need to control the four direction lights. Based on the above analysis, we can roughly understand the categories to be implemented, namely: 1 and Road, which represent the categories of travel routes. Because some vehicles are randomly generated for each line, therefore, we do not need to list a vehicle class separately. It can be directly used as a member variable of the route class. 2. Lamp class indicates the traffic light class on each line. Because there are only 12 fixed lines and no one line can be listed separately, it is most appropriate to use enumeration to define this class. 3. The LampController class controls Lamp objects. 4. Main class of a running program. Next we will analyze the specific functions of each class. Road class, 1. Each line must have an attribute that represents its own name. Select String. 2. Each thread needs a table that can be added or deleted (corresponding to the vehicles driving at the intersection and driving after the intersection) to indicate the vehicles on the line. Select ArrayList. 3. A car is opened every 2-10 seconds and requires a separate thread to be implemented through a timer. When a vehicle is opened, it is loaded into the ArrayList. If a vehicle is taken away, It is deleted from the list. The vehicle uses the line name_id. 4. Check the status of the corresponding light. If the light is green, a car is driven every second and deleted from the ArrayList. A separate thread is also required. [Java] <span style = "font-size: 14px"> 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; public class Road {// indicates the vehicle set private List <String> vechicles = new ArrayList <String> (); // route name private String n Ame = null; public Road (String name) {this. name = name; // enable a timer in the constructor to check whether the light in this direction is green every second, // print the vehicle collection and remove the first vehicle from the collection. // Create a thread pool and use the Executor of a single worker thread to run the thread in the unbounded queue mode. ExecutorService pool = Executors. newSingleThreadExecutor (); // create a Runnable implementation Class Object and execute the given command at a certain time in the future. Pool.exe cute (new Runnable () {public void run () {int id = 1; while (true) {// a car is driven every 2-10 seconds and implemented using thread sleep, the new car is added to the end of the collection, indicating that later try {Thread. sleep (new Random (). nextInt (9) + 2) * 1000);} catch (InterruptedException e) {e. printStackTrace ();} vechicles. add (Road. this. name + "_" + id ++) ;}}); // check whether the light on the road is green every second, delete ScheduledExecutorService timer = Executors from the set. newScheduledThreadPool (1); time R. 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) + "crossing! ") ;}}}, // Task 1 to be executed, // the first execution delay time 1, // the time difference between the two operations TimeUnit. SECONDS // The unit of the set time is SECONDS) ;}</span> Lamp class, 1, fixed 12 lines, so there are 12 corresponding Lamp instances, the above analysis shows that only four lines need to be controlled. 2. Each lamp has a status display, green (true) and red (false ), in addition, when the light on a line turns red or green, the light on the line needs to be synchronized with it, and the light on the next line also needs to change to a green light. 3. Because the time for direct and left-turn green lights is different, you need to introduce the Direction (Direction) interface and add a property direction to indicate the Direction of the Light Route [java] <span style = "font-size: 14px"> public interface direction {/* indicates the route travel method, there are three values: */public static final int LEFT =-1; public static final int CENTER = 0; public static final int RIGHT = 1; int getDirection ();} </span> [java] <span style = "font-size: 14px"> import java. util. date; enum Lamp implements ction {// each enumeration element represents each Direction of the control Lamp S 2N ("N2S", "S2W", CENTER, false), S2W ("N2E", "E2W", LEFT, false), E2W ("W2E", "E2S ", CENTER, false), E2S ("W2N", "S2N", LEFT, false), // corresponds to the lights in the four directions stated above, and N2S (null, null, CENTER, false), N2E (null, null, LEFT, false), W2E (null, null, CENTER, false), W2N (null, null, LEFT, false ), // when the RIGHT turn signal is on, the green light is S2E (null, null, RIGHT, true), E2N (null, null, RIGHT, true), N2W (null, null, RIGHT, true ), w2S (null, null, RIGHT, true); private String opposite; // indicates the light private String next to the route; // indicates the light private boolean lighted of the next route; // Lamp status private int ction; // indicates the direction of the Lamp route, which may be LEFT \ CENTER \ RIGHT private Lamp (String opposite, String next, int direction, boolean lighted) {this. opposite = opposite; this. next = next; this. direction = direction; this. lighted = lighted;} public boolean isLighted () {return lighted; // judge the Light status, Highlighted indicates a green light, black indicates a red light} public int getDirection () {// gets the direction of the Light Route return direction;} // Changes the current light to a green light, at the same time, the opposite light will change public void light () {this. lighted = true; if (opposite! = Null) {Lamp. valueOf (opposite ). light ();} System. out. println (name () + "the green light is on. A total of six directions can be seen below! ") ;}// Turns the current light and the light in the corresponding direction into a red light, and the light on the next route turns green, returns the change to the green light public Lamp blackOut () {this. lighted = false; if (opposite! = Null) {Lamp. valueOf (opposite). blackOut ();} Lamp nextLamp = null; if (next! = Null) {nextLamp = Lamp. valueOf (next); nextLamp. light (); System. out. println ("green light from" + name () + "--------> switch to" + next); System. out. println ("Time:" + new Date () ;}return nextLamp ;}</span> LampController class, 1, the entire system only needs a traffic light controller, so, this class should be designed as a singleton. 2. During running, you must specify the first green light, so it is best to specify it in the constructor. 3. Two timers are used to control the light for both direct and left turns. The green light time for direct traffic is 20 seconds, and the green light time for left turns is 15 seconds. [java] <span style = "font-size: 14px "> import java. util. concurrent. executors; import java. util. concurrent. scheduledExecutorService; import java. util. concurrent. timeUnit; class LampController {// indicates the current light private Lamp currentLamp; public LampController () {// specifies that the light from south to north is the green light currentLamp = Lamp first. s2N; currentLamp. light ();/* indicates the first running delay time */int festTime; if (currentLamp. getDirection () = Direction. CENTER) {festTime = 20;} else {festTime = 15;} ScheduledExecutorService timer = Executors. newScheduledThreadPool (1);/* Create a timer. If the current light is in the direct line, the green light is given for 20 seconds. If the current light is in the left direction, it is set to 15 seconds */timer. scheduleWithFixedDelay (new Runnable () {public void run () {currentLamp = currentLamp. blackOut ();/* if the current light is a light on a direct line, increase the green time by 5 seconds */if (currentLamp. getDirection () = Direction. CENTER) {try {Thread. sleep (5*1000);} catch (InterruptedException e) {e. printStackTrace () ;}}}, festTime, // the first execution latency of 15, // The execution cycle TimeUnit. SECONDS // the specified time unit is SECONDS); }}</span> the main class (TrafficDemo) runs the program [java] <span style = "font-size: 14px "> class TrafficDemo {public static void main (String [] args) {String [] directions = new String [] {" S2N "," S2W "," E2W ", "E2S", "N2S", "N2E", "W2E", "W2N", "S2E", "E2N", "N2W", "W2S "}; // create 12 routes for (int I = 0; I <directions. length; I ++) {new Road (directions [I]) ;}// Traffic Light Controller new LampController () ;}</span>

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.