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