从java中的对象释放锁定

时间:2013-07-04 07:18:52

标签: java notify thread-synchronization

大家好,这是我的代码,面临的问题是尽管调用了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();
    }
}

}

1 个答案:

答案 0 :(得分:6)

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

在你的情况下,很可能在线程确实有时间启动之前很久就会调用notifyAll。 (对于计算机,启动一个线程需要一个永恒的时间,比如10,000,000个时钟周期)这意味着notifyAll会丢失。 (它只通知当时正在等待的线程)