我想在线程内做一些事情,返回他作为字符串所做的事情,并且我想等待该字符串做其他事情。我一直在阅读wait()
和notify()
但我不明白。谁能帮我吗?
这里我创建了执行操作的线程
new Thread(
new Runnable() {
@Override
public void run() {
synchronized(mensaje) {
try {
mensaje.wait();
mensaje = getFilesFromUrl(value);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
在这里我等待字符串 mensaje 更改
如果字符串不是“”,那么我会显示一个按钮和一些文本
synchronized(mensaje) {
if (mensaje.equals("")) {
try {
mensaje.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
btnOk.setVisibility(View.VISIBLE);
lblEstado.setText(mensaje);
}
所有这些东西都在一个方法内
最佳答案
notify()
、notifyAll()
和 wait()
基本上是这样工作的:
当您调用 wait()
时,它会释放同步块(synchronized block)占用的互斥锁,并将当前线程置于队列中 hibernate 状态。
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
以及相应的执行器。
关于java - 不知道如何在Java中使用wait()和notify(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16623801/