【发布时间】:2012-07-08 04:49:26
【问题描述】:
我有这门课:
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();
}
}
}
【问题讨论】:
-
在构造函数中启动一个线程很少是一个好主意。不确定这是否是问题所在。例如:stackoverflow.com/questions/5623285/…
-
你是对的,但我已经更改了我的代码,但仍然无法正常工作。
-
我看不出重点是将
canAccess首先设置为false,然后在使用此变量的唯一synchronized块中设置true。 -
我是否更正了您创建 10 个 MyThread 类实例,然后调用每个方法的 start()。您能否提供一段代码,这将显示更好的画面。我猜每个线程都在等待自己的实例,没有人唤醒它们。
-
@MarkoTopolnik 对不起,我不明白。如果我设置 canAccess = true 并调用 notifyAll,理论上我应该有“线程竞赛”或者我错过了什么?
标签: java multithreading wait notify