2016-05-16 123 views
0

我想从主线程运行一个线程,我希望此线程在主线程完成后执行。 我该怎么做? 我可以通过线程引用主线程并调用join()方法吗?如何确保一个线程在其主线程完成后执行?

+4

如果你不希望他们同时运行做产生的线程等待CountDownLatch之前它所需要,并有主线程完成,为什么还需要2个线程? –

+0

我希望它可以同时运行,但只要确保主要完成之前... – Sharon182

+0

您希望主线程在......之前完成?和Scott Hunter所说的一样:你有一个主线程来做某事。我不知道它做了什么,但让我们调用它是'M()'。然后在'M()'完成之后还有其他你想要发生的事情。我们称之为'S()'。为什么你的主线程不能简单地执行'M()'然后执行'S()'?你最近想完成什么? (即什么是'S()'?) –

回答

1

最接近的将是一个shutdownHook

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

但这可能会运行过程中仍然活着,一旦进程死亡,多数民众赞成它,则不能将任何线程加入那并不是一个过程再也不存在了。

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

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 
+0

你为什么说“人为地”?你为什么认为'Runtime.getRuntime()。addShutdownHook(...)'是一个更好的解决方案?原来的问题是[XY问题](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem):OP没有告诉我们她想完成什么。她都专注于她所想的是解决她的问题,但我们不知道实际问题是什么。 –

+0

@jameslarge我认为提到'addShutdownHook'的答案在本质上是更好的,因为功能范围很广,而我的答案通过加入一个线程来做到这一点。这就是说,它可能被认为是实现这一目标的另一种方式。 – Mena

+0

@james放大这说,阅读评论回来,这是有点不清楚OP要什么 - 我同意。 – Mena

0

这种情况的典型的同步是一个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 
} 
相关问题