Return object from Thread [duplicate]
Matthew Harrington
I am wondering if there is a good way to return an object from a running thread. In my android project (not important for the question) I have this method:
public void getFolders()
{ Thread t = new Thread(new Runnable() { @Override public void run() { List<File> result = new ArrayList<File>(); Files.List request = null; do { try { request = service.files().list(); request.setQ("'appdata' in parents"); FileList files = request.execute(); result.addAll(files.getItems()); request.setPageToken(files.getNextPageToken()); } catch (IOException e) { System.out.println("An error occurred: " + e); request.setPageToken(null); } } while (request.getPageToken() != null && request.getPageToken().length() > 0); } }); t.start();
}This method grabs some data from the internet and store the result in List<File> result. That's why I do not want to run it in the UI thread. Now I want to return this List to my main method. What is the best way to do this?
2 Answers
public interface Callable<V>A task that returns a result and may throw an exception. Implementors define a single method with no arguments called call.
The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.
EDIT:Also you should be using AsyncTask in android for doing background tasks and not create threads of your own.
1You should use Callable interface instead of Runnable interface to create threads. Callable interface offers a call() method, which can return an Object.
Because you cannot pass a Callable into a Thread to execute, you instead use the ExecutorService to execute the Callable object. The service accepts Callable objects to run by way of the submit() method:
<T> Future<T> submit(Callable<T> task)As the method definition shows, submitting a Callable object to the ExecutorService returns a Future object. The get() method of Future will then block until the task is completed.
You can follow the sample on this link and customize it according to your requirement: