'Java multithreading :Start 2 threads, print 1-100 by turns. result like this: but it is not running [duplicate]
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.
Solution 1:[1]
If you use wait and notify, a thread that waits needs to be able to expect another thread to call notify on the SAME OBJECT INSTANCE that wait was called on. You’re not doing that, one thread synchronizes on an instance of Thread1 and the other instance synchronizes on an instance of Thread2. The result is the threads enter wait and nothing wakes them up.
For locking to work the lock has to be shared. The wait and notify methods use the implicit lock being synchronized on as a coordination point, when a thread calls notify on the object synchronized on, only threads that called wait on that object can be woken up.
Solution 2:[2]
Because you are using a new Thread(new MyThread1("Thread1"));
In family guy term. Plagio di plagio
Remove the "new Thread" and just use
Thread t1 = new MyThread1("Thread1");
Also, why Runnable and not callable and then print?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Augusto |
