Java 等待来自线程的事件



我有一个主线程的应用程序。在 A 点,我创建一个执行某些操作的子线程。同时,主应用程序线程不应停止。

在 B 点,子线程到达中间解决方案。它现在需要来自主应用程序线程的输入。我怎样才能做到这一点?

我不能使用 wait((/notify((,因为主应用程序线程不应该等待(即 ui 事件仍应处理(。我设想这样的东西(简化/伪共生(:

主线程:

public void foo(){
child = new Thread();
child.start();
...
return;
}
...

public void receiveEventFromChildProcess(){
bar();
}

孩子

Public void start(){
run();
}
Public void run(){
bla();
//Intermediate solution reached
notifyMainApplicationThread();
}

这可行吗?我承认我可能根本没有正确处理这个问题。但是感谢您的帮助:)

我认为您可以使用CountDownLatch来实现您的用例。我在这里提供一个例子。

public class Main {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(1);
Thread worker = new Thread(new Worker(countDownLatch));
worker.start();
// do some work in mian
// now the point reached and you want wait main therad for notification from child therad
countDownLatch.await(); //main will wait at this ponit still the child thread did not call countDownLatch.countDown();
}
}
class Worker implements Runnable {
CountDownLatch countDownLatch;
Worker(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
// bla();
countDownLatch.countDown(); // it will notify the main thread to resume its work
// notifyMainApplicationThread();
}
}

使用带有可调用对象的执行器可能会有所帮助。像这样:

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<MyClass> result = executor.submit(new MyCallable());

例如,当您从子进程获得结果时,您可以将其传递给通知主线程的某个侦听器。

最新更新