The Callable interface is similar to Runnable, which can be seen from the name, but Runnable will not return the result and cannot throw an exception that returns the result. Callable is more powerful. After being executed by a thread, it can return the value. This return value can be Get it by Future, that is, Future can get the return value of asynchronous execution of tasks. Let's take a simple example below
The code copy is 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 {
// Receive the exception caught in the run method, and then the custom method throws the 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>() {//Use the Callable interface as the constructor parameter
public String call() {
//The real task is executed here, the return value type here is String, which can be of 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); //Get the result, and set the timeout execution time to 5 seconds. You can also use future.get() to obtain results without setting the execution timeout.
} catch (InterruptedException e) {
//System.out.println("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 instance of FileNotFoundException)
throw (FileNotFoundException) exception;
if (exception instanceof IOException)
throw (IOException) exception;
}*/
}