我有一个线程,只有在特定情况下才需要工作。否则它会在一个空的无限循环中迭代:
public void run() {
while(true) {
if(ball != null) {
// do some Calculations
}
}
}
循环实际上什么也不做,但每次迭代都必须检查是否需要进行计算,这会影响性能吗? 对我来说,仅在需要时创建线程不是一个选择,因为我的实现Runnable的类是一个可视化对象,必须始终显示。
编辑:那么以下解决方案好吗?还是使用其他方法更好(涉及性能)?
private final Object standBy = new Object();
public void run() {
while(true) {
synchronized (standBy) {
while(ball != null) // should I use while or if here?
try{ standBy.wait() }
catch (InterruptedException ie) {}
}
if(ball != null) {
// do some Calculations
}
}
public void handleCollision(Ball b) {
// some more code..
ball = b;
synchronized (standBy) {
standBy.notify();
}
}
BlockingQueue
;这个无限循环会占用你所有的 CPU 时间。 - twentylemonball
已被设置。 - meriton