为了提问方便,写了一段程序,不明白为什么notify不能唤醒wait。预期输出应该是不停的输出1,为什么只输出一个1,然后就不动了?
class Test implements Runnable { public void run() {
try {
while (true) {
System.out.print(1);
synchronized (this) {
wait();
notify();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}public class bk { public static void main(String[] args) {
Test t = new Test();
new Thread(t).start();
}}
class Test implements Runnable { public void run() {
try {
while (true) {
System.out.print(1);
synchronized (this) {
wait();
notify();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}public class bk { public static void main(String[] args) {
Test t = new Test();
new Thread(t).start();
}}
线程不太懂,我再想想。顺便等高人来
wait时都已经停止了哦,怎么会执行下面的代码呢?
要写另外一个线程,调用notifyAll()/notify(),才能把他救出来呀.
你的线程住于等待状态
你却又想让他去唤醒自己好像 没有 自己已经熟睡的 还可以随时叫醒自己 API 参考~。~
class Test implements Runnable { public void run() {
try {
while (true) {
System.out.print(1);
synchronized (this) {
this.wait();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}class Test1 implements Runnable { private Test test = null;
Test1(Test t){test = t;}
public void run() {
while (true) {
synchronized (test) {
test.notify();
}
}
}
}public class bk { public static void main(String[] args) {
Test t = new Test();
new Thread(t).start();
Test1 t1 = new Test1(t);
new Thread(t1).start();
}}
http://topic.csdn.net/u/20080326/17/7d00ce09-7d4c-4faf-9e15-d9fd324b60ac.html