The callable interface is similar to the runnable, it can be seen from the name, but Runnable will not return the result, and can not throw the return of the result of the exception, and the callable function is more powerful, after the thread executes, can return the value, this return value can be future to get , which means that future can get the return value of the asynchronous execution task, and here's a simple example
Copy Code code as follows:
Package com.future.test;
Import java.io.FileNotFoundException;
Import java.io.IOException;
Import java.util.concurrent.Callable;
Import java.util.concurrent.ExecutionException;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.FutureTask;
Import Java.util.concurrent.TimeUnit;
Import java.util.concurrent.TimeoutException;
public class MyTest {
Receives the exception caught in the Run method, and then the custom method throws an exception
private static Throwable exception;
/**
* @param args
*/
public static void Main (string[] args) {
TODO auto-generated Method Stub
String result = "";
Executorservice executor = Executors.newsinglethreadexecutor ();
futuretask<string> future =
New Futuretask<string> (New callable<string> () {//Using callable interface as a constructor parameter
Public String call () {
The real task is executed here, where the return value type is string and can be any type
try {
Thread.Sleep (10000);
catch (Interruptedexception e) {
TODO auto-generated Catch block
Exception = e;
E.printstacktrace ();
}
return "11111";
}});
Executor.execute (future);
You can do anything else here.
try {
result = Future.get (5000, timeunit.milliseconds); Gets the result, setting the timeout execution time to 5 seconds. You can also use Future.get () without setting the execution timeout to get results
catch (Interruptedexception e) {
SYSTEM.OUT.PRINTLN ("The task has been cancelled");
Future.cancel (TRUE);
catch (Executionexception e) {
Future.cancel (TRUE);
catch (TimeoutException e) {
Future.cancel (TRUE);
finally {
Executor.shutdown ();
}
SYSTEM.OUT.PRINTLN ("Result:" +result);
}
/* public void ThrowException () throws FileNotFoundException, IOException {
If (Exception instanceof FileNotFoundException)
Throw (FileNotFoundException) exception;
If (Exception instanceof IOException)
Throw (IOException) exception;
}*/
}