大家好,这是我的代码,我面临的问题是尽管调用了 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();
}
}
}
最佳答案
当您使用 notifyAll 时,您还应该更改状态,而当您使用 wait 时,您应该检查该状态更改。
在您的情况下,很可能会在线程真正有时间启动之前很久就调用 notifyAll。 (对于计算机来说,启动一个线程需要一个永恒的时间,比如 10,000,000 个时钟周期)这意味着 notifyAll 丢失了。 (它只通知那一刻实际上正在等待的线程)
关于java - 从java中的对象释放锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17464087/