I made a thread like this one bellow:
public class MyThread implements Runnable {
private int temp;
public MyThread(int temp){
this.temp=temp;
}
There are a few ways to "share" variables with Threads.
The problem with your code is that you are passing an int
which is passed by value. This means that temp
and this.temp
is not the same variable.
Using a Future
as other answers suggest is one way that you can share variables. Using a Future
, you can ensure that the Thread has finished before actually fetching the result of that Threads execution so might be more relevant to you.
Other ways of sharing variables among Threads that are Thread-safe, but does not guarantee that the Thread has finished execution:
set
method to set value. synchronized
getter method that returns the Threads value.