简体   繁体   中英

Java code speed improvement

Hi all may such a code cause lag of process?

while(true)
if(!connected) break;

As we see it checks for condition all the time. Would it be faster if I set small sleep in each iteration.

The code runs on Android GingerBread .

EDIT:

It waits for other Thread to finish and set variable Connected to false. Variable connected is used like lock. thread usually finds it true and waits to be false. then sets to true and only changes it at the end.

I belive it could be like this:

while(connected) {
// do stuff... 

我认为最好在循环中添加小睡眠,以便为其他进程释放处理器资源,尤其是在单核处理器上。

Try something like this:

private Integer connected;
private ConnectedListener connectedListener;

public interface ConnectedListener {
    public void onDisconnected();
}

private void startThreads() {
    for (int i = 0; i < 10; i++) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                synchronized (connected) {
                    connected++;
                }

                // do some random long work

                synchronized (connected) {
                    connected--;
                    if (connected == 0 && connectedListener != null) {
                        //let the listener know that we are completely disconnected
                        connectedListener.onDisconnected();
                    }
                }
            }
        }).start();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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