gur*_*hni 1 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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
当您使用notifyAll时,您还应该更改状态,当您使用wait时,您应该检查状态更改.
在你的情况下,很可能在线程真正有时间启动之前很久就会调用notifyAll.(对于计算机,启动一个线程需要一个永恒的时间,比如10,000,000个时钟周期)这意味着notifyAll会丢失.(它只通知当时正在等待的线程)
| 归档时间: |
|
| 查看次数: |
849 次 |
| 最近记录: |