Arj*_*jun 4 java concurrency optimization multithreading android
嗨,我想知道在不是 UI 线程的线程内的 while 循环中使用 Thread.sleep(x) 对性能有多糟糕......这不是使用 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);
}
Run Code Online (Sandbox Code Playgroud)
您应该使用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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6029 次 |
| 最近记录: |