我有一个 Java 游戏,在启动时 CPU 占用率至少高达 94%。考虑到该程序只有 124kb,这确实是一个疯狂的数字。可能的问题可能是它实现了三种线程。
- 作为服务器接收和发送数据包;
- 一个作为客户;
- 和主游戏线程。
关于为什么会发生这种情况,可能有很多不同的可能性,但我的猜测是坚持线程的想法。欢迎任何降低这个数字的想法和建议,并且非常表示赞赏。
CPU:英特尔酷睿 2 双核、2.66Ghz 内存、2GB。
<小时/> 注意:这种情况在许多计算机上都会发生,但游戏运行顺利。 <小时/> 编辑:在回复所做的回答时,我没有使用任何库,并且我以类似的方式创建了我的线程。客户端和服务器线程遵循以下规则:public class Client implements Runnable {
public boolean running;
public DatagramSocket socket;
public Client() {
running = true;
socket = new DatagramSocket(/*whatever params*/);
new Thread(this).start();
}
public void run() {
byte[] data = new byte[1024];
while(running) {
socket.receive(data);
parsePacket(data);
}
}
public void parsePacket(byte[] data) {
// Does all the packet parsing things.
// The client modifies the level.
// The server just spreads things to every client. (could be the server if multiple connections are live?)
}
}
但是,当您检查线程是否被中断时,难道不会检查是否且仅当线程被暂停吗? - 这就是线程被中断的意思,对吧?
会是 Thread.sleep(50)
在主游戏循环结束时有什么好处吗?仍然对合理的修复开放。
最佳答案
这是一个性能调整问题,需要整个代码库知道您正在做的事情会导致处理器出现峰值。现在我们知道您已经编写了一个启动三个线程的计算机程序。所以我打赌它在这三个线程之一中,因为这就是我们真正知道的。我们甚至不知道它基于什么游戏库。如果没有任何真实的代码,就无法提供任何真正的帮助。
无论如何,您可以通过以下步骤来开始找出哪条线程正在被遗忘。通常您会编写这样的主线程:
public class MainGameLoop implements Runnable {
public void startupGame() {
long start = System.currentTimeMillis();
doStartUpGame();
long end = System.currentTimeMillis();
System.out.printf("Start up took %,d%n", end - start );
}
public void run() {
startUpGame();
while( !Thread.currentThread().isInterrupted() ) {
long start = System.currentTimeMillis();
doGameLogic();
long duration = System.currentTimeMillis() - start;
System.out.printf("Processing took %,d ms %n", duration );
if( duration < frameRate ) {
Thread.sleep( frameRate - duration );
} else {
System.out.printf("Game loop took longer than it should by %,d ms%n", duration - frameRate );
}
}
}
}
在所有线程上执行此操作,然后查看三个线程中哪一个占用了这么多 CPU。之后,您可以开始缩小范围,找出哪些部分正在消耗您的 CPU。对除 doGameLogic 等之外的每个子进程重复此过程。
关于java - 进程 'javaw' 占用 CPU 使用率 95% 以上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23050962/