2014-03-25 128 views
0

另一個線程我有三個功能funcOne()funcTwo() & funcThree()被一個在主線程中調用一個:多線程:等待在主線程

public static void main(String[] args) { 
    funcOne(); 
    funcTwo(); 
    funcThree(); 
} 

我想這三個功能是在上面的順序運行。 funcOne()和funcThree()很好,因爲它們在主線程上運行。對於funcTwo(),它的任務是在花葯線程中運行:

public static void funcTwo(){ 
    Thread thread = new Thread(){ 

     @Override 
    public void run(){ 
      System.out.println("function two is running."); 
     } 
    } 
    thread.start(); 
} 

當我跑我的主要功能,我看到funcTwo()運行funcThree()後。我如何確保funcTwo()funcOne()之間運行? & funcThree()

+6

如果這三樣東西是指在順序執行,爲什麼你想並行運行它們呢? –

+0

我只是模擬我的實際任務到這個簡單的場景。 funcTwo()必須位於我的項目中的單獨線程中。你的問題是合理的,但這不是我想要的答案。 –

+3

但是,你的簡化基本上已經沒有意義:如果你需要三件事情以特定的順序發生,你不應該並行地做。如果'funcTwo()'中的工作在你開始'funcThree()'之前完成了,那麼在不同的線程上做什麼呢? –

回答

0

我不知道你想做什麼,但我認爲,是你的問題的答案。從funcTwo

public static Thread funcTwo(){ 
    Thread thread = new Thread(){ 

     @Override 
    public void run(){ 
      System.out.println("function two is running."); 
     } 
    } 
    thread.start(); 
    return thread; 
} 

funcOne(); 
Thread thread = funcTwo(); 
thread.Join(); 
funcThree(); 
+0

你爲什麼返回線程?我可以在funcTwo()裏面加入thread.join()嗎? –

+0

是的,但它是更具可讀性的代碼。 –

0

返回創建的線程對象,並funcThree

後使用的Thread.join()

或者使用CountDownLatch如果你有一個以上的線程。

1

你可以試試這個:

public static void main(String[] args) { 
    funcOne(); 
    funcTwo(); 
    funcThree(); 
} 

public static void funcOne() { 
    System.out.println("function one ran"); 
} 

public static void funcTwo(){ 
    Thread thread = new Thread(){ 
     @Override public void run(){ 
      System.out.println("function two ran."); 
     } 
    }; 
    thread.start(); 
    try { thread.join(); } catch (InterruptedException e) {} 
}  

private static void funcThree() { 
    System.out.println("function three ran"); 
} 
1
funcOne(); 
Thread thread = funcTwo(); 
thread.Join(); 
funcThree(); 

這樣做是爲了執行線程,當你打電話的Thread.join(),它會等待線程來完成,雖然這將凍結您的GUI或任何其他進程,如果線程需要一些時間,它會結束。

線程是做什麼的?

1

使用Countdownlatch:

public class MyTestClass { 
    static final CountDownLatch latch = new CountDownLatch(1); 
    public static void main(String[] args) { 

     funcOne(); 
     funcTwo(); 
     try { latch.await(); } catch (InterruptedException e) {} 
     funcThree(); 
    } 

    public static void funcOne() { 
     System.out.println("function one ran"); 
    } 

    public static void funcTwo(){ 
     Thread thread = new Thread(){ 
      @Override public void run(){ 
       System.out.println("function two ran."); 
       latch.countDown(); 
      } 
     }; 
     thread.start(); 
    } 

    private static void funcThree() { 
     System.out.println("function three ran"); 
    } 
}