2

我有一个工作线程,偶尔我会使用Handler.Post(). 在某些情况下,我需要工作线程等到Handler.Post()在 UI 线程上执行修改视图,在修改UI线程后,通知工作线程继续......这是我的简单工作线程:

workerThread = new Thread() {
    @Override
    public void run() {
        progressBarHandler.post(new Runnable() {
            public void run() {
                //Step1: which works ok
                ActionModeButton.performClick();
            }
        }

        //Step2: returns null pointer exception because ActionMode
        //is not yet created and R.id.select_recording is an
        //ActionMode button if I put Thread.sleep(1000); here it
        //will work fine.
        final View selectRecording = getActivity()
                .findViewById(R.id.select_recording);
        selectRecording.post(new Runnable() {
            public void run() {
                selectRecording.performClick();
            }
        });
    }
}
workerThread.start();
4

2 回答 2

4

使用带等待和通知的同步块

final Handler handler = new Handler();
    final Object lock = new Object();
    new Thread(new Runnable() {
        boolean completed = false;
        @Override
        public void run() {

            handler.post(new Runnable() {
                @Override
                public void run() {
                    synchronized (lock) {
                        //Do some stuff on ui thread 

                        completed = true;
                        lock.notifyAll();                            
                    }
                }
            });

            synchronized (lock) {
                try {
                  if(!completed)
                    lock.wait();
                }
                catch (InterruptedException e) {

                }
            }

        }
    }).start();
于 2013-05-24T09:57:36.103 回答
0

那使用 a 怎么样Semaphore

Semaphore semaphore = new Semaphore(0);
uiHandler.post(new Runnable() {
  // ... do something here
  semaphore.release();
});
semaphore.acquire();

从许可证Semaphore开始。0线程将一直阻塞,semaphore.acquire()直到semaphore.release()(这将添加一个许可)被调用。

于 2016-09-22T12:43:58.577 回答