我有一个工作线程,偶尔我会使用以下命令向 UI 线程发送更新Handler.Post()
。在某些情况下,我需要工作线程等待Handler.Post()
在 UI 线程上执行and视图被修改并且afterUI线程被修改,通知worker线程继续...
这是我的简单工作线程:
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();
使用带有等待和通知的同步块
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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)