Skip to content

Instantly share code, notes, and snippets.

@Abhi-Codes
Created October 14, 2023 06:33
Show Gist options
  • Save Abhi-Codes/b34cd9b9e7c7b568c07b6bfff79c7b2b to your computer and use it in GitHub Desktop.
Save Abhi-Codes/b34cd9b9e7c7b568c07b6bfff79c7b2b to your computer and use it in GitHub Desktop.
Print1To10UsingVolatileBoolean
public class Test {
private static Object object = new Object();
//private static AtomicBoolean isOddTurn = new AtomicBoolean(true);
private volatile Boolean isOddTurn = Boolean.TRUE;
public static void main(String[] args) {
Test test = new Test();
test.runDemo();
}
public void runDemo() {
OddPrinter oddPrinter = new OddPrinter(isOddTurn, object);
EvenPrinter evenPrinter = new EvenPrinter(isOddTurn, object);
new Thread(oddPrinter).start();
new Thread(evenPrinter).start();
}
class OddPrinter implements Runnable {
private int counter = 1;
private Boolean isOddTurn;
private Object object;
OddPrinter(Boolean isOddTurn, Object object) {
this.isOddTurn = isOddTurn;
this.object = object;
System.out.println("Odd");
System.out.println(this.isOddTurn.hashCode());
System.out.println(isOddTurn.hashCode());
}
@Override
public void run() {
synchronized (object) {
while (counter <= 10) {
while (!isOddTurn) {
try {
object.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println(counter);
counter += 2;
isOddTurn=Boolean.FALSE;
object.notify();
}
}
}
}
class EvenPrinter implements Runnable {
private int counter = 2;
private Object object;
private Boolean isOddTurn;
EvenPrinter(Boolean isOddTurn, Object object) {
this.isOddTurn = isOddTurn;
this.object = object;
System.out.println("Evem");
System.out.println(this.isOddTurn.hashCode());
System.out.println(isOddTurn.hashCode());
}
@Override
public void run() {
synchronized (object) {
while (counter <= 10) {
while (isOddTurn) {
try {
object.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println(counter);
counter += 2;
isOddTurn=Boolean.TRUE;
object.notify();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment