【问题标题】:Android threading, locks, concurrent exampleAndroid 线程、锁、并发示例
【发布时间】:2017-04-28 17:48:49
【问题描述】:

嗨,我想知道在不是 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);
}

【问题讨论】:

    标签: java android multithreading optimization concurrency


    【解决方案1】:

    您应该使用synchronized 块来依赖wait/notify/notifyAll 来同步您的线程,您甚至不需要修改任何状态,任何共享@987654325 @instance 就足够了。

    代码可能是:

    // 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();
    }
    

    【讨论】:

    • 我将此标记为答案,因为它会重写代码而不涉及睡眠。但是我正在寻找更多的理论答案
    • 题外话:你放慢了速度;我几乎又要赶上你了……继续前进,只剩下 1.5K 了 ;-) (今天尽我所能提供帮助 ;-)
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-06-25
      • 1970-01-01
      • 1970-01-01
      • 2018-10-11
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多