top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How can I return value from Java Thread ?

+1 vote
739 views
How can I return value from Java Thread ?
posted Jul 6, 2015 by Pardeep Kohli

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

This is an example of how to return the value of a Thread.

We have implemented two classes, RetDouble and RetInt that both implement the Callable, the first using as parameter a Double and the second one using as parameter an Integer. They both override the call() method of the Callable, and the first returns a Double value, whereas the second one returns an Integer.

We create an ExecutorService, using newFixedThreadPool(int nThreads) API method of Executors. The method returns a thread pool that reuses a fixed number of threads operating off a shared unbounded queue.

The ExecutorService uses its submit(Callable task) API method, for both Callables in order to submit a value-returning task for execution and returns two Future objects representing the pending results of the tasks.

In order to get the values of the Future objects, we can use their get() API methods, that wait if necessary for the computation to complete, and then retrieve the result.

Finally the ExecutorService uses its shutdown() API method to initiate an orderly shutdown, in which the previously submitted tasks are executed, but no new tasks will be accepted.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class RetVal {
    public static void main(String args[]) throws Exception { 
  ExecutorService service = Executors.newFixedThreadPool(3); 
  Future<Double> retdouble = service.submit(new RetDouble());
  Future<Integer> retInt = service.submit(new RetInt());
  System.out.println(retdouble.get());
  System.out.println(retInt.get()); 
  service.shutdown();    
    }
}

class RetDouble implements Callable<Double> {
    RetDouble() {
    }
    @Override
    public Double call() {
  return 2.0;
    }
}

class RetInt implements Callable<Integer> {
    RetInt() {
    }
    @Override
    public Integer call() {
  return 1;
    }
}
answer Jul 8, 2015 by Karthick.c
...