1

大家好,这是我的代码,我面临的问题是,尽管调用notifyAll,它没有释放锁,请你说明原因并告诉解决方案。我是线程新手。提前致谢。

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

}
4

1 回答 1

6

当您使用 notifyAll 时,您还应该更改状态,当您使用 wait 时,您应该检查状态更改。

在您的情况下,很可能在线程真正有时间开始之前很久就会调用 notifyAll 。(对于一台计算机,启动一个线程需要很长时间,比如 10,000,000 个时钟周期)这意味着 notifyAll 丢失了。(它只通知那一刻实际上正在等待的线程)

于 2013-07-04T07:22:00.173 回答