0

我想在一个线程中做一些事情,将他所做的事情作为字符串返回,我想等待那个字符串做其他事情。我一直在阅读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);
}

所有这些东西都在一个方法中

4

1 回答 1

1

notify(),基本上是这样工作的notifyAll()wait()

当您调用wait()它时,它会释放同步块占用的互斥锁,并将当前线程放入队列中休眠。

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

和相应的执行者。

于 2013-05-18T11:45:12.140 回答