gpt4 book ai didi

java - Android 线程、锁、并发示例

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:57:52 28 4
gpt4 key购买 nike

您好,我想知道在非 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);
}

最佳答案

你应该使用一个synchronized block 来依赖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();
}

关于java - Android 线程、锁、并发示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41124965/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com