0

我有 2 个工作要在 JAVA 中执行。我有:

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

   takeInfofromDB2();
   doSomeLongCalculationsWithThatData2();

   GenerateAnswerFromBothAnswers();
}

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

4

2 回答 2

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);

您不应该按原样运行此代码(我尚未对其进行测试,如果您getResult之前调用可能会发生奇怪的事情join),但它应该作为如何以基本方式使用线程的起点。

于 2013-03-17T18:44:31.757 回答
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();
}
于 2013-03-18T06:50:21.630 回答