Two threads needs to print in this order-
Thread1:0
Thread2:::0
Thread1:1
Thread2:::1
Thread1:2
Thread2:::2
Thread1:3
Thread2:::3
Thread1:::4
Thread2:::4
.
.
.
Thread1:100
Thread2:::100
...
Currently this is my code, somehow it gets stuck. . Not sure why it is not running as expected
public class Solution{
private volatile boolean isOneTurn;
public Solution(){
isOneTurn = true;
}
public void test(){
Thread t1 = new Thread(new MyThread1("Thread1"));
Thread t2 = new Thread(new MyThread2("Thread2"));
t1.start();
t2.start();
}
class MyThread1 implements Runnable {
public String name;
public MyThread1(String name) {
this.name = name;
}
@SneakyThrows
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
synchronized (this) {
if (!isOneTurn){
this.wait();
}
System.out.println(name + "-" + i);
isOneTurn = false;
this.notifyAll();
}
}
}
}
class MyThread2 implements Runnable {
public String name;
public MyThread2(String name) {
this.name = name;
}
@SneakyThrows
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
synchronized (this) {
if (isOneTurn){
this.wait();
}
System.out.println(name + "-" + i);
isOneTurn = true;
this.notifyAll();
}
}
}
}
}
I know there are many similar question out there. But I am just wondering why my code is not working as expected.