Java wait and notify deadlock

I want to start two threads one by one without using sleep () or Locks, but there is a dead end! What happened to my code? I used wait () and notifyAll () and an 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) { } } } } } 
+5
source share
2 answers

Running the code and looking at it, I found that each thread you created generates and synchronizes with its own object, therefore it does not allow them to notify each other. I also found that you are waiting before notifying, so never come to the o.notifyAll() call since o.wait() stops it first.

Change final Object o = new Object() to static final Object o = new Object() and switch places o.wait() and o.notifyAll()

+7
source

I think the synchronized block is causing a dead end. Because it will not start another thread until it completes. You use the wait() method to wait() for the current thread. Well, it will wait, but since it is in the synchronized block, it will be in the current thread forever so that no other thread appears due to synchronized .

One thing you can do to make another thread work is to use Thread.stop . Try calling the stop method on the current stream link. But I'm not sure if this will allow the current thread to start again.

-1
source

All Articles