I have a method with a HandlerThread
. A value gets changed inside the Thread
and I'd like to return it to the test()
method. Is there a way to do this?
public void test() { Thread uiThread = new HandlerThread("UIHandler"){ public synchronized void run(){ int value; value = 2; //To be returned to test() } }; uiThread.start(); }
When creating a multithreaded program, we often implement the runnable interface. Runnable does not have a return value. To get the return value, Java 5 provides a new interface Callable, which can get the return value in the thread.
ThreadStart delegates in C# used to start threads have return type 'void'. If you wish to get a 'return value' from a thread, you should write to a shared location (in an appropriate thread-safe manner) and read from that when the thread has completed executing.
If you want to return only status of the thread (say whether the thread completed what it intended to do) then just use pthread_exit or use a return statement to return the value from the thread function.
pthread_exit() is used to return a value from the thread back to the main process.
Usually you would do it something like this
public class Foo implements Runnable { private volatile int value; @Override public void run() { value = 2; } public int getValue() { return value; } }
Then you can create the thread and retrieve the value (given that the value has been set)
Foo foo = new Foo(); Thread thread = new Thread(foo); thread.start(); thread.join(); int value = foo.getValue();
tl;dr
a thread cannot return a value (at least not without a callback mechanism). You should reference a thread like an ordinary class and ask for the value.
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