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.