Last active
May 6, 2019 13:34
-
-
Save matiangul/9dde933f46fbc799a0bed7d08c9104ff to your computer and use it in GitHub Desktop.
Hello World Threads!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package pl.angulski.example.threads; | |
enum State { | |
HELLO("Hello "), | |
WORLD("world"), | |
EXCLAMATION("!\n"); | |
private final String text; | |
State(String text) { | |
this.text = text; | |
} | |
boolean isAllowed(State to) { | |
return to.ordinal() - 1 == this.ordinal() || this == EXCLAMATION && to == HELLO; | |
} | |
String getText() { | |
return text; | |
} | |
} | |
class StateMachine { | |
private static StateMachine INSTANCE = null; | |
private State state = State.EXCLAMATION; | |
private StateMachine() { | |
} | |
static synchronized StateMachine getInstance() { | |
if (INSTANCE == null) { | |
INSTANCE = new StateMachine(); | |
} | |
return INSTANCE; | |
} | |
private boolean isNotAllowedToPrint(State state) { | |
return !this.state.isAllowed(state); | |
} | |
private void transition() { | |
State[] values = State.values(); | |
state = values[state.ordinal() + 1 % values.length]; | |
} | |
Thread thread(int times, State state) { | |
return new Thread(() -> { | |
for (int i = 0; i < times; i++) { | |
synchronized (INSTANCE) { | |
while (isNotAllowedToPrint(state)) { | |
try { | |
INSTANCE.wait(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
throw new RuntimeException(e); | |
} | |
} | |
System.out.print(state.getText()); | |
transition(); | |
INSTANCE.notifyAll(); | |
} | |
} | |
}); | |
} | |
} | |
class HelloWorldCommand { | |
static void run(int times) { | |
StateMachine sm = StateMachine.getInstance(); | |
Thread helloThread = sm.thread(times, State.HELLO); | |
helloThread.start(); | |
Thread worldThread = sm.thread(times, State.WORLD); | |
worldThread.start(); | |
Thread exclamationThread = sm.thread(times, State.EXCLAMATION); | |
exclamationThread.start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment