Multi-threaded Combat (a): Traffic light Management system

Source: Internet
Author: User

I. Project requirements:

Simulate the intersection of traffic lights management system logic, the specific requirements are as follows:

1. Asynchronously randomly generates vehicles that follow each route.
For example:
Vehicles travelling north from south to----straight vehicles
Vehicles from West to south----turn right.
Vehicles from east to south----left-turn vehicles
。。。
2. Lights ignore the yellow light, only consider the red and green light.

3. The left Turn vehicle control signal should be considered, and the right turn vehicle is not controlled by the signal.

4. The specific signal control logic is the same as the ordinary traffic light control logic in real life, regardless of the control logic under special circumstances.

Note: North-South vehicles and things to the vehicle alternately released, the same direction waiting for the vehicle should be released straight vehicles and then released left-turn vehicles.

5. Each car passes the intersection time is 1 seconds (hint: can simulate by the way of the thread sleep).

6. Randomly generated vehicle time interval and traffic light Exchange time interval custom, can be set.

7. Do not require the implementation of the GUI, only consider the system logic implementation, log mode can show the results of the program operation.


Two. Demand Analysis:

There are a total of 12 routes, in order to unify the programming model, you can assume that each route has a traffic light to control it, the right turn of the 4 route control lights can be assumed to be called the Evergreen State, in addition, the other 8 lines are 22 pairs, can be grouped into 4 groups, so, The program simply takes into account the sequence of the control lights of the 4 routes labeled with the number numbers, and the control lights of the 4 routes in the opposite direction follow the 4 route switches without extra consideration.



Three. Object Modeling:

Let's take a tentative look at what the objects are: traffic lights, traffic lights, cars, routes. Does the car cross the road when it sees the light that corresponds to its route? No, also need to see whether there is a car in front of it, to see if there is a car, which object to ask? The road, where the collection of vehicles is stored, obviously there should be a way to increase the number of vehicles and reduce the number of vehicles on the road. Look at the topic, we do not have to reflect the process of vehicle movement, but to capture the vehicle through the intersection of the process, that is, to capture the road to reduce the process of a car, so this car does not need to be designed as an object, with a string representation on it. Object-oriented design holds an important lesson: who owns the data and who provides the means to manipulate the data externally.


there will be multiple cars on each route, and a new car will be randomly added to the route, and a car will be reduced every second during the green light. a road class is designed to represent the route, and each road object represents a route with a total of 12 routes, that is, a total of 12 road instance objects are generated in the system. Each route is randomly added to a new vehicle, which is added to a collection to save. Each route is checked every second to see if the light that controls the route is green, and the first car in the collection of this route is removed, which means the car has crossed the junction.


To design a lamp class to represent a traffic light, each traffic light maintains a state: bright (green) or not bright (red), each traffic light should have a way to lighten and darken, and can return their own bright black state. There are 12 routes in total, so there are 12 traffic lights to be generated in a total system. The right turn of the route is not controlled by the lights, but in order to allow the program to adopt a unified approach, it is assumed that there are four right turning lights, but these lights are solid state, that is never black. In addition to the lights on the other 8 routes in the right corner, they are 22 paired and can be grouped into 4 groups, so as soon as the programming process is taken out of each of the 4 groups , the lights are turned on, and the lamps corresponding to the 4 lights change with each other, so Lamp class to have a variable to remember their own opposite direction of the light, in a lamp object in the light and darken method, the corresponding direction of the light is also lightened and blackened. When each lamp turns black, the lamp is illuminated with the next one, and the lamp class uses a variable to remember its next light. No matter where in the program to get the lights in a certain direction, every time you get the same instance object, the lamp class instead of using enumerations to do is obviously very convenient, always only the 12-directional lamp instance object.


Design a Lampcontroller class that periodically turns the current green light red


Four. Program implementation:

1. Road:

public class Road {private List<string> vechicles = new arraylist<string> ();p rivate string name;public Road (string name) { THIS.name = name;//Opens a thread: simulating a vehicle's ongoing random journey, 1-10s will produce a car executorservice pool = executors.newsinglethreadexecutor (); Pool.execute (New Runnable () {public void run () {for (int i = 1; i <; i++) {try {thread.sleep (New Random (). Nextint (ten) + 1) * +), Vechicles.add (Road.this.name + "_" + i);} catch (Interruptedexception e) {e.printstacktrace ();}}}); /Turn on timer: check if the corresponding light is green every second, then 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 road object has a name member variable to represent the direction, and there is a vehicles member variable to represent the vehicle collection in the direction.
In the construction method of the Road object, start a thread every other random time to add a car to the vehicles collection (represented by a string in the form of a "route name _id").
Start a timer in the construction method of the road object, checking that the light is green in that direction every second, and then printing the vehicle collection and removing the first car in the collection.


2. Lamp:

/** * Each lamp element represents a light in one direction, with a total of 12 directions, all with a total of 12 lamp elements. * Like the upward light below, each two form a group, a group of lights turn green or red at the same time, so the program code only need to control a lamp in each group of lights can: * s2n,n2s * s2w,n2e * e2w,w2e * e2s,w2n *-------* s2e,n2w * E2 N,w2s * Above the last two lines of the lights are virtual, because from south to east and from west to north, and their corresponding direction is not controlled by traffic lights, so you can imagine they always green. */public enum Lamp {//Each enumeration element represents a control light of One Direction s2n ("N2s", "s2w", false), s2w ("n2e", "e2w", false), e2w ("w2e", "E2s", false), E2s ( "W2n", "s2n", false),//The following elements represent lights in the opposite direction of the above elements, their "opposite direction light" and "next light" should be ignored! N2S (null, NULL, FALSE), n2e (null, NULL, FALSE), w2e (null, NULL, FALSE), w2n (null, NULL, FALSE),//from south to east and from west to north, right-turning lights are not controlled by traffic lights, So, it can be assumed that they are always green s2e (null, NULL, TRUE), e2n (null, NULL, TRUE), n2w (null, NULL, TRUE), w2s (null, NULL, TRUE);p rivate Lamp (strin G opposite, String Next, Boolean lighted) {this.opposite = Opposite;this.next = next;this.lighted = lighted;} Whether the current light is a green private Boolean lighted;//corresponding to the current light at the same time as the green, private string opposite;//The current light becomes red a green lamp private string next;public Boolean islighted () {return lighted;} /** * When a light turns green, it corresponds to the direction of the lamp will also be 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 below to see the car through!" ");} /** * When a lamp turns red, the light in the corresponding direction will turn red, and the light in the next direction will turn green * @return the next lamp to turn green */public lamp BlackOut () {this.lighted = False;if (opposite! = nul L) {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;}}

In the system, there are 12 lights in the direction, in the other places of the program to obtain the corresponding lamp instance object according to the lamp name, synthesize these factors, the lamp class uses the enumeration form in the Java5 the definition to be simpler.


The light black state in each lamp object is represented by the lighted variable, and the lamp objects in the four directions of s2n, s2w, e2w and e2n are then polled to lighten, and there is a oppositelampname variable in the Lamp object to indicate their opposite direction, A nextlampname variable is used to represent the next lighted light after the light is turned on. These three variables are assigned in the form of a constructor, because the enumeration elements must be referenced after the definition, so they cannot be referenced to each other in the constructed method, so the lights in the opposite direction and the next direction are represented in string form.


To increase the lamp to lighten and darken the method: Light and Blackout, for s2n, s2w, e2w, e2n in the four direction of lamp objects, the two methods inside to let the opposite direction of the lights and darken, blackout method also to make the next light to lighten.
In addition to the lamp objects in the four directions of s2n, s2w, e2w, e2n, the Nextlampname and Oppositelampname properties of lamp objects in other directions are set to NULL, and s2n, s2w, e2w, E2n the Nextlampname and Oppositelampname properties of lamp objects in these four directions must be set to NULL to prevent light and blackout from entering a dead loop.


3. Lampcontroller

public class Lampcontroller {private lamp currentlamp;public Lampcontroller () {//Just start to turn the light from south to north to green; currentlamp = lamp.s2n; Currentlamp.light ();//Turn on timer: Turn the current green light to red every 10 seconds and turn the light in the next direction to green scheduledexecutorservice timer = Executors.newscheduledthreadpool (1); Timer.scheduleatfixedrate (new Runnable () {public void run () {Currentlamp = Currentlamp.blackout ();}}, ten, ten, Timeunit.seconds);}}
The whole system can only have a traffic light control system, so the Lampcontroller class is best designed as a single case.
Lampcontroller the first green light to be set in the construction method.
The Start method of the Lampcontroller object turns the current light green and then starts a timer that turns the current light red and turns the next light green every 10 seconds.


4. MainClass:

public class MainClass {public static void main (string[] args) {//generates 12 directions of route 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 ();}}
creates an object representing 12 alignments with a for loop. It then obtains the Lampcontroller object and invokes its Start method.


<< This blog excerpt from "Wisdom Podcast-zhangxiaoxiang" >>


Multi-threaded Combat (a): Traffic light Management system

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.