如何确保在主线程完成后执行一个线程?

时间:2016-05-16 11:19:58

标签: java multithreading

我想从主线程运行一个线程,但是我想在主线程完成后执行这个线程。 我该怎么办? 我可以向线程传递对主线程的引用并调用join()方法吗?

4 个答案:

答案 0 :(得分:1)

最接近的是shutdownHook

Runtime.getRuntime().addShutdownHook(new Thread(){
  ...
});

但是这将会运行,这个过程仍然存在,一旦过程消失,就是这样,你就不能将任何线程添加到一个不再存在的过程中。

答案 1 :(得分:1)

您可以使用Runtime.getRuntime()方法。这是一个例子:

public static void main(String[] args) {
    .....
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable(){
        public void run(){
            // run when the main thread finishes. 
        }
    }));
}

您可以在documentation

中找到有关此内容的更多详情

答案 2 :(得分:0)

您可以使用基本线程对象人为地执行此操作,但我建议使用关闭钩子上的其他答案。

public static void main(String[] args) throws Exception {
    // parametrizes with current thread
    new Deferrable(Thread.currentThread());
    System.out.println("main thread");
}

static class Deferrable extends Thread {
    Thread t;

    Deferrable(Thread t) {
        this.t = t;
        // optional
        // setDaemon(true);
        start();
    }

    @Override
    public void run() {
        try {
            // awaits termination of given Thread before commencing
            t.join();
            System.out.println("other thread");
        } catch (InterruptedException ie) {
            // TODO handle
        }
    };
}

这将始终打印:

main thread
other thread

答案 3 :(得分:0)

这种情况的典型同步器是CountDownLatch。让生成的线程在执行它需要之前等待CountDownLatch,并通过调用CountDownLatch.countDown()完成主线程

public static void main(String[] args) {
    final CountDownLatch latch = new CountDownLatch(1); // will need only one countDown to reach 0
    new Thread(() -> {
        try {
            latch.await(); // will wait until CountDownLatch reaches 0

            // do whatever is needed

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }).start();

    // do stuff

    // end main thread

    latch.countDown(); // will make the latch reach 0, and the spawned thread will stop waiting
}
相关问题