Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning value from Thread

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(); } 
like image 694
Neeta Avatar asked Feb 05 '12 11:02

Neeta


People also ask

Can a thread return a value JAVA?

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.

How does thread call method return value?

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.

How do you return a value from a Posix thread?

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.

Which function is used to return a value from the thread back to the main process in Linux?

pthread_exit() is used to return a value from the thread back to the main process.


1 Answers

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.

like image 95
Johan Sjöberg Avatar answered Oct 12 '22 22:10

Johan Sjöberg