过程';javaw';占95%+;CPU使用率的统计
我有一个java游戏,它在启动时至少需要94%的CPU。考虑到程序只有124kb,这确实是一个疯狂的数字。可能的问题是它实现了三种线程过程';javaw';占95%+;CPU使用率的统计,java,multithreading,performance,cpu-usage,Java,Multithreading,Performance,Cpu Usage,我有一个java游戏,它在启动时至少需要94%的CPU。考虑到程序只有124kb,这确实是一个疯狂的数字。可能的问题是它实现了三种线程 一个作为服务器接收和发送数据包 一个作为客户 和主要的游戏线索 可能有许多不同的可能性来解释为什么会出现这种情况,但我的猜测是坚持线程的观点。欢迎您提出任何降低该数字的想法和建议,非常感谢 CPU:Intel Core 2 Duo,2.66Ghz RAM,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 );
}
}
}
}
public类MainGameLoop实现可运行{
公共游戏(){
长启动=System.currentTimeMillis();
doStartUpGame();
long end=System.currentTimeMillis();
System.out.printf(“启动时间%,d%n”,结束-启动);
}
公开募捐{
startUpGame();
而(!Thread.currentThread().isInterrupted()){
长启动=System.currentTimeMillis();
doGameLogic();
长持续时间=System.currentTimeMillis()-开始;
System.out.printf(“处理时间%,d毫秒%n”,持续时间);
if(持续时间<帧速率){
睡眠(帧率-持续时间);
}否则{
System.out.printf(“游戏循环花费的时间比它应该花费的时间长%,d毫秒%n”,持续时间-帧速率);
}
}
}
}
在所有线程上都这样做,看看这三个线程中哪一个占用了这么多CPU。在这之后,你可以开始缩小它的范围到什么部分是消耗你的CPU。对doGameLogic等之外的每个子进程重复此过程。jvm在cpu消耗较高时创建了多少线程?另外,通过监视GC活动来检查jvm是否在执行GC时让自己忙起来。大小通常不表示CPU负载<代码>while(true){}非常容易地占用100%的CPU!Thread.isInterrupted()是一个在有人调用Thread.Interrupted()时设置的标志,当您希望某个线程关闭时会执行该操作。interrupt()不会关闭线程,它只是请求线程停止。阅读JavaAPI中的线程,因为它们并不难从API中理解。睡眠调用可以防止线程烧坏CPU,因为您只需要以游戏的帧速率更新屏幕,而无需更多。如果没有睡眠,你基本上是在(真的){砰的一声处理器}的时候写的。中断异常是非常重要的,并且与上面的内容联系在一起。