Let's say we have this simple example:
public Example extends Thread{      String temp;          public Example(){     }      @Override     public void run(){         .         .         .         .         temp = "a_value";     }      public static void main(String[] args) {          Example th = new Example();         th.start();     }  } How can the Thread after finishing its job return me the String temp?
How to Return Values From a Thread. A thread cannot return values directly. The start() method on a thread calls the run() method of the thread that executes our code in a new thread of execution. The run() method in turn may call a target function, if configured.
Short Answer: When a thread has finished its process, if nothing else holds a reference to it, the garbage collector will dispose of it automatically.
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.
format(bar) return 'foo' + baz from multiprocessing. pool import ThreadPool pool = ThreadPool(processes=1) async_result = pool. apply_async(foo, ('world', 'foo')) # tuple of args for foo # do some other stuff in the main process return_val = async_result. get() # get the return value from your function.
Make use of the (relatively) new Callable<T> instead of Runnable (available in 1.5 and newer versions):
Here is a (simple) example:
import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future;   public class Main {      public static void main(final String[] argv) {         final ExecutorService service;         final Future<String>  task;          service = Executors.newFixedThreadPool(1);                 task    = service.submit(new Foo());          try {             final String str;              // waits the 10 seconds for the Callable.call to finish.             str = task.get(); // this raises ExecutionException if thread dies             System.out.println(str);         } catch(final InterruptedException ex) {             ex.printStackTrace();         } catch(final ExecutionException ex) {             ex.printStackTrace();         }          service.shutdownNow();     } }  class Foo implements Callable<String> {     public String call() {         try {             // sleep for 10 seconds             Thread.sleep(10 * 1000);         } catch(final InterruptedException ex) {             ex.printStackTrace();         }          return ("Hello, World!");     } } 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