Domanda

hello guys this is my code , problem am facing is that despite calling notifyAll, it is not releasing the lock , can you please state the reason and tell the solution. Am new to threads. Thanks in advance.

class Lock1 {}

class Home1 implements Runnable {
private static int i = 0;

private Lock1 object;
private Thread th;

public Home1(Lock1 ob, String t) {

    object = ob;
    th = new Thread(this);
    th.start();
}

public void run() {
    synchronized (object) {

        while (i != 10) {
            ++i;
            System.out.println(i);
        }
        try {
            // System.out.println("here");
            object.wait();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }
        System.out.println("here thread 1");
    }
}
 }

class Home2 implements Runnable {
private static int i = 0;

private Lock1 object;
Thread th;

public Home2(Lock1 ob, String t) {

    object = ob;
    th = new Thread(this);
    th.start();
}

public void run() {
    synchronized (object) {

        while (i != 10) {
            ++i;
            System.out.println(i);
        }
        try {
            // System.out.println("here");
            object.wait();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }
        System.out.println("here thread 2");

    }
}

  }

public class Locking {

public static void main(String arg[]) {
    Lock1 ob = new Lock1();

    new Home1(ob, "thread 1");
    new Home2(ob, "thread 2");
    synchronized (ob) {
        ob.notifyAll();
    }
}

}
È stato utile?

Soluzione

When you use notifyAll, you should also have a state changed and when you use wait, you should check that state change.

In your case it is likely that notifyAll will be called long before the threads really have time to start. (For a computer, starting a thread takes an eternity, like 10,000,000 clock cycles) This means the notifyAll is lost. (It only notifies threads which are actually waiting right at that moment)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top