gpt4 book ai didi

java等待来自线程的事件

转载 作者:行者123 更新时间:2023-12-02 11:08:59 29 4
gpt4 key购买 nike

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

在B点,子线程到达中间解。现在它需要来自主应用程序线程的输入。我怎样才能实现这个目标?

我不能使用wait()/notify(),因为主应用程序线程不应该等待(即ui事件仍然应该被处理)。我设想这样的事情(简化/伪验证):

主线程:

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

...


public void receiveEventFromChildProcess(){
bar();
}

child

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();
}
}

关于java等待来自线程的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50724551/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com