Reputation: 90
i want to run 2 codes simultaneously in java so i used thread.here i want to get the results from both thread 1 and thread 2 .Please help Also im not getting thread.getResults i think its not working is there any way to get the results
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();
Upvotes: 2
Views: 191
Reputation: 184
I would like to suggest another simple solution.
Object result1;
Object result2;
Thread thread1 = new Thread( () -> {
takeInfofromDB();
result1 = doSomeLongCalculationsWithThatData();
});
Thread thread2 = new Thread( () -> {
takeInfofromDB2();
result2 = doSomeLongCalculationsWithThatData();
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
Then you don't need additional getResult()
method. You can just use result1
and result2
after calling joins.
Upvotes: 0
Reputation: 7521
thread1
and thread2
are instances of Thread
class, which doesn't have getResult()
method. You have to create your own non-anonymous classes that extends Thread
.
public class Db1Thread extends Thread {
private Object result;
@Override
public void run() {
takeInfofromDB();
result = doSomeLongCalculationsWithThatData();
}
public Object getResult() {
return result;
}
}
And then
Db1Thread thread1 = new Db1Thread();
thread1.start();
thread1.join();
Object result1 = thread1.getResult();
P.S. the better approach is to use CompletableFuture
from Java 8+. Here is the brief guide https://www.baeldung.com/java-completablefuture
Upvotes: 0
Reputation: 12346
This is exactly the job for a Future.
ExecutorService service = Executors.newFixedThreadPool(2);
Future<Object> future1 = service.submit( ()->{
takeInfofromDB();
return doSomeLongCalculationsWithThatData();
} );
Future<Object> future2 = service.submit( ()->{
takeInfofromDB2();
return doSomeLongCalculationsWithThatData2();
} );
Object result1 = future1.get();
Object result2 = future2.get();
Also, on another note. With java 11 and higher you can use var.
var thread1 = new Thread() {
private Object result;
@Override
public void run() {
takeInfofromDB();
result = doSomeLongCalculationsWithThatData();
}
public Object getResult() {
return result;
}
}
Then it retains your new methods.
thread1.start();
thread1.join();
Object result = thread1.getResult();
Upvotes: 4