Skip to content

Instantly share code, notes, and snippets.

@rxrav
Created October 5, 2023 09:53
Show Gist options
  • Save rxrav/a52bf9e207d0c6cc22ba7d2390da431b to your computer and use it in GitHub Desktop.
Save rxrav/a52bf9e207d0c6cc22ba7d2390da431b to your computer and use it in GitHub Desktop.
package com.github.rxrav.java21bootcamp;
public class JavaRocks {
private final int times;
private boolean shouldPrintJava = true;
public JavaRocks(int times) {
this.times = times;
}
public synchronized void printJava(Runnable action) throws InterruptedException {
for (int i = 0; i < this.times; i ++) {
if (shouldPrintJava) {
action.run();
shouldPrintJava = false;
notify();
}
wait();
}
// when print-java is done, notify print-rock to complete
// so, it doesn't wait any longer...
notify();
}
public synchronized void printRocks(Runnable action) throws InterruptedException {
for (int i = 0; i < this.times; i ++) {
if (!shouldPrintJava) {
action.run();
shouldPrintJava = true;
notify();
}
wait();
}
}
public static void main(String[] args) throws InterruptedException {
var javaRocks = new JavaRocks(10);
var javaPrinter = Thread.ofPlatform()
.name("java-printer")
.unstarted(() -> {
try {
javaRocks.printJava(() -> System.out.print("Java "));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
var rocksPrinter = Thread.ofPlatform()
.name("rock-printer")
.unstarted(() -> {
try {
javaRocks.printRocks(() -> System.out.print("Rocks!\n"));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
javaPrinter.start();
rocksPrinter.start();
javaPrinter.join();
rocksPrinter.join();
}
}
@rxrav
Copy link
Author

rxrav commented Oct 5, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment