简体   繁体   English

程序运行缓慢并随着时间的推移降低性能

[英]Slow program and reducing performance over time

My program is a Java game which involves taking turns between the user and AI. 我的程序是一个Java游戏,涉及在用户和AI之间轮流进行。 Therefore after all operations are complete I have a infinite while loop which only breaks after the turn has changed. 因此,在所有操作完成之后,我有一个无限的while循环,该循环仅在转弯发生变化后才会中断。 I only use an infinite loop because I am using a timer and cannot predict when the user ends their turn. 我只使用一个无限循环,因为我使用的是计时器,无法预测用户何时结束回合。 But I notice that my program slows down over time to a point where even clicking buttons has no effect. 但是我注意到我的程序随着时间的推移会变慢,甚至单击按钮也无效。 Is it my loop which is causing this? 是我的循环导致了这个吗? Help would be appreciated. 帮助将不胜感激。

while(true) {
    if(playerTurn % 2 == 1) {
        artificialIntelligence();
        break;
    }
}

Without more code, it is hard to determine what is the real cause of the problem. 没有更多的代码,很难确定问题的真正原因是什么。 However, one suspect may be that you're holding on to object references and they're not being reclaimed by garbage collection. 但是,一个怀疑者可能是您坚持使用对象引用,而垃圾回收没有回收它们。 Try using a java profiler, it can help you to pin point where exactly the issue may arise. 尝试使用Java探查器,它可以帮助您查明可能出现问题的确切位置。

If you use an infinite loop(while loop in your case) this operation would be performed continuously; 如果您使用无限循环(在您的情况下为while循环),则该操作将连续执行; thus slowing your application. 因此减慢了您的应用程序。 Hence, I would suggest breaking the code into two threads . 因此,我建议将代码分成两个线程

First thread - Check user-turn event. 第一个线程 -检查用户转向事件。

Second thread - Do the AI stuff. 第二线程 -做AI的事情。

As soon as the user event occurs, stop the thread and do what's needed. 一旦发生用户事件,请停止线程并执行所需的操作。 This way your code would never be blocked at any point of time; 这样,您的代码将永远不会在任何时间被阻塞。 thus resulting in better performance. 从而获得更好的性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM