[go: up one dir, main page]

Skip to content

Commit

Permalink
Added Enumeration classes
Browse files Browse the repository at this point in the history
  • Loading branch information
syndersage committed Jul 22, 2022
1 parent 9e70f69 commit a15eb96
Show file tree
Hide file tree
Showing 2 changed files with 99 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/main/java/com/randomtasks/enumerations/EnumDemo1.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.randomtasks.enumerations;

public class EnumDemo1 {
public enum Transport {
CAR(10), TRUCK(10), AIRPLANE(10), BOAT(10), TRAIN(10);
int speed;
Transport(int speed) {
this.speed = speed;
}
}
public static void main(String[] args) {
try {
System.out.println(Transport.valueOf("CAR1"));
}
catch (IllegalArgumentException e) {
System.out.println("Illegal argument in enum list");
}
Transport tp1 = Transport.CAR;
Transport tp2 = Transport.CAR;
tp2.speed = 20;
System.out.println(tp1.speed);
System.out.println(Transport.BOAT.ordinal());
}
}
75 changes: 75 additions & 0 deletions src/main/java/com/trythis/c12/t01/TrafficLightDemo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package com.trythis.c12.t01;

import com.randomtasks.enumerations.EnumDemo1;
import com.randomtasks.multithreading.threadImplementsRunnable.MyThreadDemo;

enum TrafficLight {
RED(5), GREEN(5), ORANGE_BEFORE_RED(2), ORANGE_BEFORE_GREEN(2);
private int time;
public int getTime() {
return time;
}
TrafficLight(int time) { this.time = time; }
}

class TrafficLightController implements Runnable {
private TrafficLight light;
private boolean stop = false;
private boolean change = false;

TrafficLightController() {
light = TrafficLight.RED;
}

TrafficLightController(TrafficLight light) {
this.light = light;
}

@Override
public void run() {
while (!stop) {
changeColor();
announcer();
}
}

synchronized private void changeColor() {
try {
Thread.sleep(light.getTime() * 1000L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
switch (light) {
case RED -> light = TrafficLight.ORANGE_BEFORE_GREEN;
case ORANGE_BEFORE_GREEN -> light = TrafficLight.GREEN;
case GREEN -> light = TrafficLight.ORANGE_BEFORE_RED;
case ORANGE_BEFORE_RED -> light = TrafficLight.RED;
}
change = true;
notify();
}

synchronized public void announcer() {
while (!change) {
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println("Traffic light color changed. Current color is " + light);
change = false;
}
}

public class TrafficLightDemo {
public static void main(String[] args) {
Thread thread = new Thread(new TrafficLightController(), "Traffic light");
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}

0 comments on commit a15eb96

Please sign in to comment.