2013-03-17 30 views
0

我有2个职位我想在JAVA中执行。我有:2个线程执行2个类似职位

public static void main(String[] args) 
{ 
    takeInfofromDB(); 
    doSomeLongCalculationsWithThatData(); 

    takeInfofromDB2(); 
    doSomeLongCalculationsWithThatData2(); 

    GenerateAnswerFromBothAnswers(); 
} 

是否有可能以某种方式把takeInfofromDB();doSomeLongCalculationsWithThatData();在2个线程?至少有一个仍在工作时,GenerateAnswerFromBothAnswers();无法执行?

+2

是的,它是可能的。 – 2013-03-17 18:12:18

+0

当然这是可能的。你有什么尝试? – 2013-03-17 18:20:28

+0

@JBNizet我试着创建2个独立的类,但我不想要2个单独的类。此外,无法获得'GenerateAnswerFromBothAnswers();'仅在2个线程完成时才能工作 – lily 2013-03-17 18:40:19

回答

0

就像这个...

public static void main(String[] args) 
{ 
    Thread t1 = new Thread(new Runnable() { 
     public void run() { 
      takeInfofromDB(); 
      doSomeLongCalculationsWithThatData(); 
     }}); 

    Thread t2 = new Thread(new Runnable() { 
     public void run() { 
     takeInfofromDB2(); 
     doSomeLongCalculationsWithThatData2(); 
     }}); 

    t1.start(); 
    t2.start(); 

    t1.join(); 
    t2.join(); 

    GenerateAnswerFromBothAnswers(); 
} 
0

对于一个非常简单的轻量级方法,请尝试下面的代码。然而,你可能想了解更多有关线程,并最终执行者:http://docs.oracle.com/javase/tutorial/essential/concurrency/

Thread thread1 = new Thread() { 
    private Object result; 

    @Override 
    public void run() { 
     takeInfofromDB(); 
     result = doSomeLongCalculationsWithThatData(); 
    } 

    public Object getResult() { 
     return result; 
    } 
} 

Thread thread2 = new Thread() { 
    private Object result; 

    @Override 
    public void run() { 
     takeInfofromDB2(); 
     result = doSomeLongCalculationsWithThatData2(); 
    } 

    public Object getResult() { 
     return result; 
    } 
} 

thread1.start(); 
thread2.start(); 
thread1.join(); 
thread2.join(); 

Object result1 = thread1.getResult(); 
Object result2 = thread2.getResult(); 

GenerateAnswerFromBothAnswers(result1, result2); 

的是你不应该运行这段代码(我没有测试它,如果你join之前调用getResult可能发生奇怪的事情) ,但它应该成为如何以基本方式使用线程的起点。