threads

Return a value from a thread

This is an example of how to return the value of a Thread. The steps of the example are described in short:

  • 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;
    }
}

Output:

2.0
1

  
This was an example of how to return the value of a Thread in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button