java等待来自线程

时间:2018-06-06 15:48:08

标签: java multithreading

我有一个有主线程的应用程序。在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();
}

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

2 个答案:

答案 0 :(得分:1)

我认为您可以使用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();
        }
    }

答案 1 :(得分:0)

使用带有callables的执行程序可能会对您有所帮助。类似的东西:

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

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