Android线程、锁、并发示例

4

你好,我想知道在非UI线程中使用Thread.sleep(x)的while循环对性能有多大影响,它会占用CPU周期吗?例如:

boolean[] flag = {false};    

//New thread to show some repeated animation
new Thread(new Runnnable{ run() {
    while(true){
        someImageView.animate()....setListener(.. onComplete(){ flag[0] = true; } ..).start();
    }

}).start()

//Wait for flag to be true to carry on in this thread
while(!flag[0]){
     Thread.sleep(100);
}
2个回答

5

为了使您的线程同步,您应该使用synchronized块,并依靠wait/notify/notifyAll。在您的情况下,您甚至不需要修改任何状态,任何共享的Object实例都足够了。

代码如下:

// Mutex to share between the threads waiting for the result.
Object mutex = new Object();
...
onComplete() { 
    synchronized (mutex) {
        // It is done so we notify the waiting threads
        mutex.notifyAll();
    }
}

synchronized (mutex) {
    // Wait until being notified
    mutex.wait();
}

我将此标记为答案,因为它在不涉及sleep的情况下重写了代码..但是我正在寻找更多理论上的答案。 - Arjun
离题:你的速度慢下来了,我又快要追上你了...继续加油,只剩1.5K了;-)(今天我已经尽力帮忙了;-) - GhostCat

1

您实际上可以在线程上使用.join()来等待其完成,因此

Thread thread = new Thread(new Runnnable{ run() {
    while(true){
        someImageView.animate()....setListener(..).start();
    }

});
thread.start();
thread.join();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接