java多线程的问题,wait以后,怎么无法notifyAll
主要是实现 testthread 中创建3个线程,调用isDataChange()方法,如果数据没有改变,则线程wait,阻塞,如果数据变化,通过调用dataChange(),唤醒阻塞的线程. 发现无法唤醒线程.各位兄弟帮我看看怎么回事啊?
testthread.java
public class testthread{
public static void main(String args[]){
tThread tThread1 = new tThread();
tThread1.start();
tThread tThread2 = new tThread();
tThread2.start();
tThread tThread3 = new tThread();
tThread3.start();
}
class tThread extends Thread{
private Notificationth nsbd;
public tThread(){
initNotificationthread();
}
private void initNotificationthread(){
try{
nsbd = Notificationth.getInstance();
}
catch (Exception e){
e.printStackTrace();
}
}
/**
* Thread's run method.
*/
public void run(){
while (true){
if ((nsbd != null) && (nsbd.isDataChanged())) {
System.out.print("test thread change!");
}
else{
System.out.print("test thread no change!");
break;
}
}
}
}
}
Notificationth.java
public class Notificationth{
public static Notificationth manager= new Notificationth();
public Notificationth() {
}
public static Notificationth getInstance() {
return manager;
}
public synchronized boolean isDataChanged() {
try {
System.out.print("begin wait!");
wait();
System.out.print("has notify!");
// break;
}
catch (Exception ignored) {}
return true;
}
/**
* <p>
* 当服务端收到数据改变事件后,用该方法激活所有阻塞在该对象上的线程。
* </p>
*/
public synchronized void dataChanged() {
//log.info("Current Thread Name in DataChanged: " + Thread.currentThread().getName());
notifyAll();
System.out.print("data has changed!");
}
}
testthread2.java
public class testthread2{
public Notificationth nth;
public static void main(String args[]){
Notificationth.getInstance().dataChanged();
}
}
当运行testthread.java,显示begin wait!
我再运行testthread2.java,模拟一个数据改变的消息,发现线程无法唤醒,还是阻塞!
谢谢!