你好傢伙這是我的代碼,面臨的問題是,儘管調用了notifyAll
,它並沒有釋放鎖,請你說明原因並告訴解決方案。對線程來說是新的。提前致謝。在java中釋放鎖對象
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();
}
}
}
嗨 - 你能否提供一個更詳細的解釋,說明你試圖用你的代碼實現什麼? – robjohncox
我不明白爲什麼你有重複的類「Home1」和「Home2」?你究竟想要達到什麼目標? – Multithreader
我只是玩線程,在這裏試圖釋放所有的鎖,並完成程序的執行。這裏執行沒有完成。 –