Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java wait and notify makes deadlock

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) {
                }
            }
        }
    } 
}
like image 840
John Avatar asked May 16 '15 05:05

John


1 Answers

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()

like image 86
Ben Avatar answered Sep 22 '22 18:09

Ben