2014-03-25 129 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"); 
    } 
}