I made a thread like this one bellow:
public class MyThread implements Runnable {
private int temp;
public MyThread(int temp){
this.temp=temp;
}
@Override
public void run() {
temp+=10;
return;
}
public int getTemp() {
return temp;
}
}
but when i try to use temp by getTemp i get 0
class Main {
MyThread foo = new MyThread(10);
Thread a = new Thread(foo);
a.start();
int aa = foo.getTemp();
System.out.println(aa);
}
i just want to use the calculation i did in thread to be stored in some variables for later use.
Or simply add
...
a.start();
a.join(); // Add this
...
to wait for the thread to finish before getting the result.
Your problem is that you're trying to get the result before it has been calculated. You should wait for the thread to finish before getting the result. This answer is perhaps not the best but is the simplest. As other people had already used the Executors class I didnt want to repeat their answers. I would, however, familiarise yourself with Thread and its methods before moving onto Executors to help you get a better understanding of threads as, from your post, it appears you may be a novice in this area.
Thanks to l4mpi (on the meta site) for pointing out the lack of explanation.
Use Callable instead of a Runnable, it will return a Future that you can use to retrieve the value once it is done.
You can use a named class instead of a lambda expression if you want to.
import java.util.concurrent.*;
public class ReturnValueFromThread {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Object> foo = executor.submit(() -> {
return doWork();
});
System.out.println("We will reach this line before doWork is done.");
System.out.println(foo.get()); // Will wait until the value is complete
executor.shutdown();
}
private static double doWork() throws Exception {
Thread.sleep(2000);
return Math.random();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With