我想在一个线程中创建一些返回他所做的字符串的东西,并且我想等待该字符串做其他的。我一直在阅读有关wait()
和notify()
的内容,但我得到了它。任何人都可以帮助我吗?
在这里,我创建了执行操作的线程
new Thread(
new Runnable() {
@Override
public void run() {
synchronized(mensaje) {
try {
mensaje.wait();
mensaje = getFilesFromUrl(value);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
在这里我等待字符串menaje更改
如果字符串不是“”,那么我会显示一个按钮和一些文本
synchronized(mensaje) {
if (mensaje.equals("")) {
try {
mensaje.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
btnOk.setVisibility(View.VISIBLE);
lblEstado.setText(mensaje);
}
所有这些东西都在方法
中答案 0 :(得分:0)
notify()
,notifyAll()
和wait()
基本上是这样的:
当你调用wait()
时,它会释放synchronized块占用的互斥锁,并将当前线程置于队列中。
notify()
从队列前面抓取一个等待的线程。该线程重新获取互斥锁并继续运行。
notifyAll()
唤醒队列中的所有线程。
这里使用的是一些伪代码(缺少异常处理等等):
// in the thread that is supposed to wait
synchronized {
while(!someCondition) {
wait();
}
// At this point the other thread has made the condition true and notified you.
}
// In the other thread
synchronized {
// Do something that changes someCondition to true.
notifyAll();
}
编辑: 或者正如Thilo首先写的那样看看java.util.concurrent。可能已经有针对您的用例的现成解决方案。那么就不需要使用低级构造。
更正:您的用例有一个现成的解决方案: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html
和相应的执行人。