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

Source: Internet
Author: User

I. Project requirements:

Simulation realizes traffic light management system logic at intersection. Detailed requirements such as the following:

1. Asynchronously randomly generates a vehicle that travels according to each route.


Like what:
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. Detailed signal control logic is the same as the normal traffic light control logic in real life. Control logic is not considered under special circumstances.

Note: The north-South vehicle and east-west vehicles are alternately released. In the same direction, wait for the vehicle to release the vehicle before releasing the left.


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. Just consider the system logic implementation, can show the program execution result by the log way.


Two. Demand Analysis:

There are always 12 routes together, in order to unify the programming model, if each route has a traffic light to control it. The control lights on the 4-way right turn can be called the Evergreen State, in addition. The other 8 lines are 22 paired and can be grouped into 4 groups, so the program only needs to consider the sequence of the control lights of the 4 routes marked with the 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 see its own route and the lights are green and cross the intersection? No, you need to see if there's a car in front of it. See if there is a car ahead, which object should I ask? To ask the way. The road stores a collection of vehicles, and obviously there should be a way to add vehicles and reduce vehicles on the road. Look at the topic again, we do not want to reflect the process of vehicle movement. It's just a process of capturing a vehicle's way through a junction, which is the process of capturing a car down the road. Therefore, the car does not have to be designed to be a single object, with a string representation can be. Object-oriented design holds an important lesson: who owns the data. Who will provide a way to manipulate the data externally.


There will be multiple cars on each route, a new car will be added randomly on the route, and a car will be lowered every second during the green light.

A road class is designed to represent a route, each road object represents a route, and a total of 12 routes are common. That is, a total of 12 road instance objects are generated in the system. New vehicles are added randomly on each route. 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), every traffic light to have a way to lighten and darken. And can return to their own bright black state. There are always 12 routes together. So. A total of 12 traffic lights will be generated in the system. The route to the right is not controlled by the light. However, in order to allow the application of a unified approach, so if there are four right turning lights, only these lights are solid state. That never turns 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. When programming, just remove one light from each of the 4 groups. In turn, the 4 lights turn on the light, and the corresponding lights in the 4 lamp direction with one of the same changes, so the lamp class to have a variable to remember their own opposite direction of the lamp, in a lamp object in the light and darken method, the corresponding direction of the light is also lightened and black. When each light turns black, the next light illuminates with the person. The lamp class also uses a variable to remember its next light.

No matter where in the program to get a light 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 have only a 12-directional lamp instance object.



Design a Lampcontroller class. It 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 to check if the light is green in that direction every second. is to print the vehicle collection and remove the first car from the collection.



2. Lamp:

/** * Each lamp element represents a light in one direction, and always has 12 directions in common. All of them collectively have 12 lamp elements. * There are lights for example in the following directions, each of the two forming 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,n2 W * e2n,w2s * The lights on the last two lines above are virtual. Because from the south to the east and from the west to the north, and their corresponding direction is not controlled by traffic lights. So, it is possible to imagine that they are always green.

*/public enum Lamp {//Each enumeration element represents a directional control light s2n ("N2s", "s2w", false), s2w ("n2e", "e2w", false), e2w ("w2e", "E2s", false), E2 S ("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, be able to imagine 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;//the corresponding direction of green at the same time as the current light private string opposite;//The current light turns red nowadays a green light private string next;public Boolean islighted () {return lighted;} /** * When a light turns green. Its corresponding direction of the lamp to 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 to see the car through! ");} /** * When a lamp turns red, the light in the direction should turn red, and the light in the next direction will turn green * @return The next light 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;}}

In the system, there are 12 lights in the direction, in the other parts of the program to be able to obtain the corresponding lamp instance object according to the lamp name. Combining these factors, it is simpler to define the lamp class with an enumeration form in Java5.


Each lamp object in the bright black state with the lighted variable, the choice of s2n, s2w, e2w, e2n in four directions of lamp objects in turn to turn on the light, lamp object also has a oppositelampname variable to indicate their opposite direction of the lamp. 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 construction method. Because enumeration elements must be referenced after they are defined, 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.


Add a way to lighten and darken lamp: light and blackout, for lamp objects in the four directions of s2n, s2w, e2w, and e2n. Inside these two methods, the lamp in the opposite direction becomes brighter and darker, and the Blackout method also brightens the next light.
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. Then start a timer. Turn the current light red and turn 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.