在使用Object.wait()方法时抛出了异常,代码如下:
/**
* 所有处理线程的等待对象
*/
private Object waitObject;
private boolean isRunning = false;
public MessageHandleRunnable(Object waitObject, ArrayBlockingQueue<String> queue){
this.waitObject = waitObject;
this.queue = queue;
}
private void handle(){
isRunning = true;
while(isRunning && !isInterrupted()) {
String result = takeMessage();
if (StringUtils.isEmpty(result)) {
try {
System.out.println(String.format("%s线程进入wait状态目前wait状态数量:%s ", name, MyMessageListener.waitThreadCountIncrease()));
waitObject.wait(10 * 60 * 1000);
System.out.println(String.format("%s线程进入wait状态目前wait状态数量:%s ", name, MyMessageListener.waitThreadCountSubstract()));
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.println(name+ "-- 处理消息:" + result);
}
}
System.out.println(name +"数据处理线程停止");
}
原因是,在使用Object的wait()、notify()、notifyAll()时,需要是线程安全的,所以必须要加上synchronized关键字。且synchronized的锁对象必须是Object本身(否则notify()、notifyAll()方法会失效),且对象必须是已经初始化的。
修改如下:
private void handle(){
isRunning = true;
while(isRunning && !isInterrupted()) {
String result = takeMessage();
if (StringUtils.isEmpty(result)) {
try {
synchronized (waitObject) {
System.out.println(String.format("%s线程进入wait状态目前wait状态数量:%s ", name, MyMessageListener.waitThreadCountIncrease()));
waitObject.wait(10 * 60 * 1000);
System.out.println(String.format("%s线程进入wait状态目前wait状态数量:%s ", name, MyMessageListener.waitThreadCountSubstract()));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.println(name+ "-- 处理消息:" + result);
}
}
System.out.println(name +"数据处理线程停止");
}