我遇到了一个奇怪的问题,这个线程从输入流中读取,特别是 readObject。线程正在阻塞调用,就像假设的那样,因为我尝试放置日志调试语句并且它显示了它的阻塞。问题是这个线程仍然被标记为在分析器中运行,它占用了我 50% 的 cpu 使用率。我有一个与此类似的线程,它可以正确阻塞,阻塞时占用 0% cpu。我对这里可能出现的问题感到困惑。
由于我是新用户,我无法发布图片,请参阅。图中绿色表示运行,黄色表示阻塞或等待。
此处 还提供未缩放的图像:
主要的
{
SocketFactory factory = SocketFactory.getDefault();
Socket tcpSocket = factory.createSocket("localhost", 5011);
IoTcpReadRunnable ioTcpReadRunnable = new IoTcpReadRunnable(new MessageProcessor()
{
@Override
public void enqueueReceivedMessage(Object message)
{
System.out.println("MessageReceived Enqueued.");
}
@Override
public void enqueueMessageToWrite(Envelope message)
{
System.out.println("Message Enqueued to Write.");
}
}, tcpSocket);
new Thread(ioTcpReadRunnable, "ClientExample IoTcpRead").start();
}
TcpRead 可运行
public final class IoTcpReadRunnable implements Runnable {
public static final Logger logger = LoggerFactory.getLogger(IoTcpReadRunnable.class);
protected MessageProcessor<MessageType> messageProcessor = null;
protected Socket tcpSocket = null;
protected ObjectOutputStream outputStream = null;
protected ObjectInputStream inputStream = null;
protected boolean connected = false;
public IoTcpReadRunnable(MessageProcessor<MessageType> messageProcessor, Socket tcpSocket)
{
this.messageProcessor = messageProcessor;
this.tcpSocket = tcpSocket;
this.init();
}
protected void init()
{
try
{
this.outputStream = new ObjectOutputStream(tcpSocket.getOutputStream());
this.outputStream.flush();
this.inputStream = new ObjectInputStream(tcpSocket.getInputStream());
}
catch (IOException ex)
{
logger.error("Tcp Socket Init Error Error ", ex);
}
}
public boolean isConnected()
{
return connected;
}
protected synchronized Object readObject() throws IOException, ClassNotFoundException
{
Object readObject = null;
//blocks here
logger.trace("{} About to block for read Object");
readObject = this.inputStream.readObject();
logger.trace("{} Read Object from Stream: {} ", "", readObject);
return readObject;
}
public void close()
{
try
{
//todo
this.connected = false;
this.outputStream.flush();
this.outputStream.close();
this.inputStream.close();
synchronized (tcpSocket)
{
this.tcpSocket.close();
}
}
catch (IOException ex)
{
logger.error("Error closing Socket");
}
}
@Override
public void run()
{
this.connected = true;
while (this.connected)
{
try
{
Object readObject = readObject();
if (readObject != null)
{
this.messageProcessor.enqueueReceivedMessage((MessageType) readObject);
}
else
{
logger.error("Read Object is null");
}
}
catch (IOException ex)
{
logger.error("TcpRecieveThread IOException", ex);
}
catch (ClassNotFoundException ex)
{
logger.error("TcpRecieveThread ClassnotFound", ex);
}
}
this.close();
}
}