I want to run two threads one after the other, without using sleep() or Locks, but a deadlock happens! What's wrong with my code? I used wait() and notifyAll() and an Object object.
public class Test {
public static void main(String[] args) throws InterruptedException {
PrintChar a = new PrintChar('a');
PrintChar b = new PrintChar('b');
Thread ta = new Thread(a);
Thread tb = new Thread(b);
ta.start();
tb.start();
}
}
class PrintChar implements Runnable {
final Object o = new Object();
char ch;
public PrintChar(char a) {
ch = a;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
synchronized (o) {
System.out.print(ch);
try {
o.wait();
o.notifyAll();
} catch (InterruptedException ex) {
}
}
}
}
}
Running your code, and looking at it, I've found that each thread you generated was generating and synchronizing to its own object, therefore preventing them from notifying each other. I've also found that you wait before notify, so you do not ever get to invoke o.notifyAll()
, as o.wait()
stops it first.
Change final Object o = new Object()
to static final Object o = new Object()
, and switch the places of o.wait()
and o.notifyAll()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With