Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- enum TrafficLightChange{
- GREEN, YELLOW, RED
- }
- class TrafficLightChangeSimulator implements Runnable{
- TrafficLightChange tlc;
- private boolean stop=false;
- private boolean change=false;
- TrafficLightChangeSimulator(TrafficLightChange tl){
- tlc=tl;
- }
- TrafficLightChangeSimulator(){
- tlc=TrafficLightChange.RED;
- }
- public void run(){
- while (!stop) {
- try {
- switch (tlc) {
- case GREEN:
- Thread.sleep(10000);
- break;
- case YELLOW:
- Thread.sleep(3000);
- break;
- case RED:
- Thread.sleep(12000);
- break;
- }
- changeColor();
- } catch (InterruptedException exc) {
- System.out.println("Прерывание потока");
- }
- }
- }
- synchronized void changeColor(){
- switch (tlc){
- case GREEN:
- tlc=TrafficLightChange.YELLOW;
- break;
- case YELLOW:
- tlc=TrafficLightChange.RED;
- break;
- case RED:
- tlc=TrafficLightChange.GREEN;
- break;
- }
- change=true;
- notify();
- }
- synchronized void waitChangeColor() {
- try {
- while(!change) wait();
- change = false;
- }catch (InterruptedException exc){
- System.out.println(exc);
- }
- }
- synchronized TrafficLightChange getColor(){
- return tlc;
- }
- synchronized void cancel(){
- stop=true;
- }
- }
- public class ShowFile{
- public static void main(String args[]) {
- TrafficLightChangeSimulator t1=new TrafficLightChangeSimulator(TrafficLightChange.GREEN);
- Thread mt=new Thread(t1);
- mt.start();
- for(int i=0; i<9;i++){
- System.out.println(t1.getColor());
- t1.waitChangeColor();
- }
- t1.cancel();
- }
- }
Add Comment
Please, Sign In to add comment