John
John

Reputation: 201

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) {
                }
            }
        }
    } 
}

Upvotes: 5

Views: 1011

Answers (2)

Ben
Ben

Reputation: 86

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

Upvotes: 7

Choxx
Choxx

Reputation: 945

I think the synchronized block is causing the deadlock. Cos it won't let the other thread start until current one finished. You are using wait() method to make the current thread wait. Ok, it will wait but since it is in synchronized block, it will be in the current thread forever never let any other thread to came into existence because of synchronized.

One thing you can do to make the other thread work is using Thread.stop. Try calling stop method in current thread's reference. But I am not sure whether it will let the current thread to start again.

Upvotes: -1

Related Questions