Java无限循环性能

LPr*_*Prc 9 java performance multithreading infinite-loop

我有一个线程,只有在某种情况进入时才需要工作.否则它只是迭代一个空的无限循环:

public void run() {
    while(true) {
        if(ball != null) {
             // do some Calculations
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当循环实际上什么都不做但它必须检查它是否必须每次迭代进行计算时,它是否会影响性能?只在需要时才创建这个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();
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 9

你可能想要考虑让线程进入休眠状态,只有在你的'ball'变量变为真时才唤醒它.有这样做,使用非常低的水平的多种方式,wait以及notify语句使用java.util.concurrent其提供了这样做的不易出错的方式类.查看条件界面的文档.像BlockingQueue这样的数据结构也是一种解决方案.


Squ*_*yMo 8

是的,它确实.这是繁忙等待的最简单实现,应尽可能避免.使用wait/notify或java.util.concurrent机制.也许您应该更具体地了解您希望获得更多有用的响应.