环境:
OS:win10
JDK:1.8
server: jetty-maven-plugin:9.2.1.v20140609
netty:4.1.18.Final
问题:
在多线程环境中使用channelhandlercontext时。必须睡眠100毫秒或更长时间才能成功发送数据,请查看代码段:
class A{
public boolean sendData(int deviceId, String hexData){
try {
if (deviceChannel.containsKey(Integer.valueOf(deviceId))) {
ChannelHandlerContext ctx = (ChannelHandlerContext)deviceChannel.get(Integer.valueOf(deviceId));
byte[] data = Command.Trans(deviceId, hexData);
ByteBuf bufAck = ctx.alloc().buffer();
bufAck.writeBytes(data);
ctx.write(bufAck);
ctx.flush();
return true;
}
} catch (Exception e) {e.printStackTrace();}
return false;
}
}
**Class B:**I did not sleep in class B, the data did not send successfully
class B{
public void trans(){
int iotAddr=123456;
String hexData="01020000162C";
A a=new A();
boolean isTransSuccess=a.sendData(iotAddr, hexData); //return true,The client does not receive the data,Look at the class C.
}
}
**Class C:**I sleep for 100 milliseconds before calling the sendData() method and the data is sent successfully
class C{
public void trans(){
int iotAddr=123456;
String hexData="01020000162C";
A a= new A();
try {
Thread.sleep(100); // sleep for 100 ms or more
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean isTransSuccess=a.sendData(iotAddr, hexData); //The client receives the data
}
}
当jvm执行thread.sleep(100)时会发生什么?
暂无答案!
目前还没有任何答案,快来回答吧!