Master_Tiroman

Светофор_Just4Fun

Oct 17th, 2019
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. enum TrafficLightChange{
  2. GREEN, YELLOW, RED
  3. }
  4.  
  5. class TrafficLightChangeSimulator implements Runnable{
  6.  
  7. TrafficLightChange tlc;
  8. private boolean stop=false;
  9. private boolean change=false;
  10.  
  11. TrafficLightChangeSimulator(TrafficLightChange tl){
  12. tlc=tl;
  13. }
  14. TrafficLightChangeSimulator(){
  15.  
  16. tlc=TrafficLightChange.RED;
  17. }
  18.  
  19. public void run(){
  20. while (!stop) {
  21. try {
  22. switch (tlc) {
  23. case GREEN:
  24. Thread.sleep(10000);
  25. break;
  26. case YELLOW:
  27. Thread.sleep(3000);
  28. break;
  29. case RED:
  30. Thread.sleep(12000);
  31. break;
  32. }
  33. changeColor();
  34.  
  35. } catch (InterruptedException exc) {
  36. System.out.println("Прерывание потока");
  37. }
  38. }
  39. }
  40.  
  41. synchronized void changeColor(){
  42. switch (tlc){
  43. case GREEN:
  44. tlc=TrafficLightChange.YELLOW;
  45. break;
  46. case YELLOW:
  47. tlc=TrafficLightChange.RED;
  48. break;
  49. case RED:
  50. tlc=TrafficLightChange.GREEN;
  51. break;
  52. }
  53. change=true;
  54. notify();
  55. }
  56.  
  57. synchronized void waitChangeColor() {
  58. try {
  59. while(!change) wait();
  60. change = false;
  61. }catch (InterruptedException exc){
  62. System.out.println(exc);
  63. }
  64. }
  65.  
  66. synchronized TrafficLightChange getColor(){
  67. return tlc;
  68. }
  69.  
  70. synchronized void cancel(){
  71. stop=true;
  72. }
  73.  
  74.  
  75.  
  76. }
  77. public class ShowFile{
  78. public static void main(String args[]) {
  79. TrafficLightChangeSimulator t1=new TrafficLightChangeSimulator(TrafficLightChange.GREEN);
  80. Thread mt=new Thread(t1);
  81. mt.start();
  82.  
  83. for(int i=0; i<9;i++){
  84. System.out.println(t1.getColor());
  85. t1.waitChangeColor();
  86. }
  87. t1.cancel();
  88. }
  89. }
Add Comment
Please, Sign In to add comment