Before Java5, threads are not return values, often for "have" return value, a lot of trouble, and the code is very difficult to write. Or just go around the ridge and take the other way. Now Java finally has a task that can return a value (also called a thread).
A task that can return a value must implement the callable interface, and similarly, a task that has no return value must runnable the interface.
After performing the callable task, you can get a future object that is called get on the object to get to the object returned by the callable task.
Here is a very simple example:
Package COM.LYC
Import java.util.concurrent.Callable;
Import java.util.concurrent.ExecutionException;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.Future;
public class Callablefuturetest {
public static void Main (string[] args) throws Executionexception, Interruptedexception {
Callablefuturetest test = new Callablefuturetest ();
Create a pool of threads
Executorservice pool = Executors.newfixedthreadpool (2);
Create two tasks with a return value
Callable C1 = Test.new mycallable ("A");
Callable C2 = Test.new mycallable ("B");
Perform tasks and get future objects
Future F1 = Pool.submit (c1);
Future F2 = Pool.submit (C2);
Gets the return value of the task from the future object and outputs it to the console
SYSTEM.OUT.PRINTLN ("----" + f1.get (). toString ());
SYSTEM.OUT.PRINTLN ("----" + f2.get (). toString ());
Close the thread pool
Pool.shutdown ();
}
Class Mycallable implements callable {
Private String oid;
Mycallable (String oid) {
This.oid = oid;
}
Public Object Call () throws Exception {
Return OID + "content returned by task";
}
}
}
Threads with return values in Java threads callable