Created
October 5, 2023 09:53
-
-
Save rxrav/a52bf9e207d0c6cc22ba7d2390da431b to your computer and use it in GitHub Desktop.
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 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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Solution to this problem https://gist.github.com/rokon12/cc1d1b3359cec8e4fdbcac6f2f1d5342