2016-05-16 96 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 
} 
相關問題