2个线程执行2个类似的工作

时间:2013-03-17 18:10:52

标签: java multithreading

我想在JAVA中执行2个作业。我有:

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

   takeInfofromDB2();
   doSomeLongCalculationsWithThatData2();

   GenerateAnswerFromBothAnswers();
}

是否有可能以某种方式将takeInfofromDB();doSomeLongCalculationsWithThatData();置于2个主题中?并且GenerateAnswerFromBothAnswers();无法执行,而至少有一个仍在工作?

2 个答案:

答案 0 :(得分:0)

对于非常简单的轻量级方法,请尝试以下代码。但是,您可能希望阅读有关Threads和最终Executors的更多信息: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)可能会发生奇怪的事情,但它应该作为一个起点如何以基本方式使用线程。

答案 1 :(得分: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();
}