0

I have web service and web service calls are handled by a Thread, so that they can run asynchronously, and also time out. But the thread is “runnable” and not “callable” so the thread cannot pass back the web service response.

I have read statement that we need to use a callable.Is their any way to return response from my runnable thread.I am posting small example can we make it to return value.

public class HelloThread extends Thread {

    public void run() {
        System.out.println("Hello from a thread!");
        String a="Hello";
    }

    public static void main(String args[]) {
        (new HelloThread()).start();
    }

}
user2354846
  • 41
  • 1
  • 5
  • 1
    As thread runs asynchronously, there is no chance for returning value from one thread to another thread. So, if they are in once class you can think of taking one global variable but that is also not effective for some situation as threads run parallelly. – Android Killer Aug 23 '13 at 06:19
  • 1
    You should take a look at the [Future](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html) interface – MadProgrammer Aug 23 '13 at 06:30

3 Answers3

4

You should pass a callback to the Thread and the thread can invoke the callback with the value when its done.

Karthik T
  • 31,456
  • 5
  • 68
  • 87
  • how to pass a callback to thread – user2354846 Aug 23 '13 at 06:47
  • 1
    Pass the callback as a object within the constructor of the thread and store it as a instance variable of your thread instance (of course you have to implement the constructor in your thread implementation). – Matthias Aug 23 '13 at 07:02
2

Instead of using an explicit thread, you can make use of the ExecutorService interface.

You can instantiate it using the Executors class, and then call submit and pass a Callable to it. This will start running the code in Callable in a different thread, and immediately return to you a Future object.

You can then call get on the Future in order to wait for the asynchronous execution of the Callable to finish, and to retrieve its result.

Flavio
  • 11,925
  • 3
  • 32
  • 36
0

You cannot return values from threads. But you may be interested in looking and using the SwingWorker. It enables you to run some work in background and can return something when it has completed using its done and get methods.

Here it is in more details

Another way is to define a variable before the thread starts running and assign some value to it inside the run method of the thread. This way you will be able to use that variable when the thread has finished. But again you have to deal with all those concurrency, and locks and other stuff.

me_digvijay
  • 5,374
  • 9
  • 46
  • 83