This functionality is achieved through the use of thread pools, available in Java, from version 1.5 on Executors Framework
Instead of creating a Thread
, you create a Pool with a Thread , and submit to it the tasks you want this Thread execute. For this your routine should implement a Callable<T>
. This is a simple interface, which has a call
method, the equivalent of run
that you would implement in an ordinary Thread, but with a subtle and powerful difference: It allows you to return a value of a type. p>
V call() throws Exception;
Let's go to the code:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Main {
public static void main(String[] args) throws Exception{
String resultado = "";
//Criando um pool de Threads com uma Thread,
//equivalente ao sua Thread
ExecutorService executor = Executors.newSingleThreadExecutor();
//ao inves de chamarmos o metodo Thread.start(), chamamos:
//executor.submit -> o que já permitirá que você obtenha um envólucro para
//o resultado
Future<String> futureResult = executor.submit(new Callable<String>() {
//Note como este não é um Runnable, e sim um Callable("primo" do Runnable)
@Override
public String call() throws Exception {
String retorno = "";
//processando
//sua lógica
// e assim por diante
retorno = "abcde";
return retorno;
}
});
//Obtendo um resultado da execucão da Thread
resultado = futureResult.get();
System.out.println(resultado);
//lembrar de chamar o shutodown no executor - para encerrar a
//execucão
executor.shutdown();
}
}
At the moment you submit your routine, the ExecutorService.submit
method will give you a Future
This Future object will give you access to the return value of this callable that was executed by your Thread. This will be done by calling the method Future.get()
Remember to call: executor.shutdown
- this will terminate the Pool, which will prevent new tasks from being executed.
* Please also read the comments in the example code. They should help you understand what is happening.