我有两个线程:
主线程部分代码(在循环体内)
try {
// 发送指令
os.write(buffer);
os.flush();
} catch (IOException e) {
e.printStackTrace();
log.error("Send command ERROR", e);
}
String[] data;
boolean valid;
try {
//设置超时时间,防止子线程在500毫秒内没返回
TimeUnit.MILLISECONDS.sleep(500);
data = modbusReader.getCache().toArray(new String[modbusReader.getCache().size()]);
valid = CRC16Calc.validate(modbusReader.getCache());
} catch (InterruptedException e) {
// 子线程主动唤醒主线程
data = modbusReader.getCache().toArray(new String[modbusReader.getCache().size()]);
valid = modbusReader.isValid();
}
// XXXXXXXXXXXXXXXXXXXXXX 经过几天的运行,程序停止在该处 XXXXXXXXXXXXX
long t = System.currentTimeMillis() - start;
log.debug("<<<<<<<<<< time=[{}] [{}] [{}] ", t, valid, Arrays.toString(data));
子线程部分代码
@Override
public void run() {
byte[] buffer = new byte[1024];
int len;
try {
while ((len = is.read(buffer)) != 0) {
for (int i = 0; i < len; i++) {
cache.add(String.format("%02X", buffer[i]));
}
// 校验数据,如果满足条件,则唤醒主线程
if (CRC16Calc.validate(cache)) {
this.valid = true;
caller.interrupt();
}
}
} catch (Exception e) {
log.error("Err in Reader of Channel {} \t {}", channelIndex, e.getMessage());
}
}