【发布时间】:2017-09-22 20:53:54
【问题描述】:
我对 java 线程编码进行了测试,但我遇到了一些基本问题。经过数小时的尝试和搜索,我决定在那里尝试!
我不明白为什么即使在我通知之后我的等待仍然被锁定:
在这里你可以找到我的代码:
public class Mymain {
public static void main(String[] args) {
for( int i=0;i<100;i++){
new ThreadClass(i).start();
}
}
}
public class ThreadClass extends Thread {
static boolean ok = false;
int id;
public ThreadClass(int i) {
id = i;
}
public void run() {
System.out.println("Thread start " + id);
Last.toDo(id);
if (id == 5)
try {
waiting();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (id != 5)
awaking();
System.out.println("thread end " + id);
}
private synchronized void awaking() {
// TODO Auto-generated method stub
if (ok) {
System.out.println("i'm " + id + " and i'm Awaking 5");
ok = false;
notify();
System.out.println("I did the notify and i'm " + id);
}
}
private synchronized void waiting() throws InterruptedException {
System.out.println("Sleeping");
ok = true;
wait();
System.out.println("Awake 5");
}
}
然后它开始循环或者它进入死锁不确定..它应该只是停止 id=5 的线程,然后下一个线程应该重新启动 id = 5..但是线程 5 在之后永远不会唤醒通知...
结果如你所见,我有 2 个线程试图唤醒线程 5,而线程 5 从一开始就一直在等待^^
【问题讨论】:
-
你能告诉我们你的输出是什么,应该是什么?
-
你能把它放在你的问题中,以便对其进行格式化以便于分析吗?
-
@WarrenDew 完成^^
-
仅作记录,您接受的答案确实不清楚,没有意义。请考虑选择另一个。
标签: java multithreading locking wait notify