gpt4 book ai didi

java - DatagramChannel 数据包监听器占用高 CPU 资源

转载 作者:行者123 更新时间:2023-12-02 07:41:36 30 4
gpt4 key购买 nike

我在 Java 中有一个用于 UDP 数据包的数据包监听器线程以及 2-3 个其他线程。

直到今天它都运行良好,但现在进程 javaw.exe 已开始使用持续 50% 的 CPU。

这是我的代码。

public class PacketListenerThread implements Runnable {
private SocketAddress receivedSocketAddress;
private DatagramChannel channel;
private ExecutorService pool;

public PacketListenerThread(DatagramChannel channel, ExecutorService pool) {
this.channel = channel;
this.pool = pool;
}

@Override
public void run() {
while (true) {
receivedSocketAddress = null;
ByteBuffer recvbuf = ByteBuffer.allocate(1400);
recvbuf.clear();
try {
receivedSocketAddress = channel.receive(recvbuf);
} catch (IOException e) {
e.printStackTrace();
}
if (receivedSocketAddress != null) {
pool.submit(new PacketHandlerRunnable(new TaskObject(receivedSocketAddress, recvbuf)));
}
}
}
}

我已经停止了所有其他线程,但该线程仍然使用“恒定”50% CPU。

最佳答案

参见Javadoc :

If a datagram is immediately available, or if this channel is in blocking mode and one eventually becomes available, then the datagram is copied into the given byte buffer and its source address is returned. If this channel is in non-blocking mode and a datagram is not immediately available then this method immediately returns null.

也许你对channel.receive(recvbuf)的调用不会阻塞,所以你正在以无限的速度循环,这解释了你的CPU负载。

关于java - DatagramChannel 数据包监听器占用高 CPU 资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11524924/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com