我有一个线程,只有在某种情况进入时才需要工作.否则它只是迭代一个空的无限循环:
public void run() {
while(true) {
if(ball != null) {
// do some Calculations
}
}
}
当循环实际上什么都不做但它必须检查它是否必须每次迭代进行计算时,它是否会影响性能?
只在需要时才创建这个Thread对我来说不是一个选项,因为实现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();
}
}