我有這個類:關於等待和notifyAll的
public class MyThread implements Runnable {
private static boolean canAccess = true;
private Thread t;
public FirstThread(String name) {
t = new Thread(this);
t.setName(name);
}
public void start() {
t.start();
}
private synchronized void accessed(String name) throws InterruptedException {
if (canAccess) {
canAccess = false;
System.out.println("Accessed " + name);
try {
Thread.sleep(5000);
} catch (Exception e) {
}
canAccess = true;
System.out.println("NOTIFY: " + name);
notifyAll();
}
System.out.println("WAIT: " + name);
wait();
}
@Override
public void run() {
while (true) {
try {
accessed(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
這是我的輸出:
Accessed 1
WAIT: 3
WAIT: 5
WAIT: 7
WAIT: 9
WAIT: 0
WAIT: 2
WAIT: 4
WAIT: 6
WAIT: 8
NOTIFY: 1
WAIT: 1
和我的應用程序凍結(死鎖狀態)。 似乎notifyAll方法不起作用。我的錯誤在哪裏?
我的主課。
public class Main {
public static void main(String[] args) {
MyThread [] threads = new MyThread[10];
for(int i=0;i<threads.length;i++) {
threads[i] = new MyThread(""+i);
threads[i].start();
}
}
}
在構造函數中啓動一個線程很少是個好主意。不知道這是否是問題。例如見:http://stackoverflow.com/questions/5623285/java-why-not-to-start-a-thread-in-the-constructor-how-to-terminate – assylias 2012-07-08 14:56:13
你說得對,但我已經改變了我的代碼,但仍然不起作用。 – CeccoCQ 2012-07-08 14:59:29
我沒有看到,在使用此var的唯一'synchronized'塊中,canAccess首先設置爲'false',然後設置爲'true'。 – 2012-07-08 14:59:59