Use Future

/ **
* Runnable interface has a problem, its method does not return a value. If the task requires a return result, it can only be saved to a variable, but also provides additional methods to read, very inconvenient.
* Java standard library also provides a Callable interface and the interface Runnable ratio, it is more of a return value
* Callable interface is a generic interface that can return the result of the specified type
* When we submit a Callable task, we will get the same time a Future object, and then we call the Future object in the main thread some point get () method, you can get the results of asynchronous execution.
* When calling get (), if the asynchronous task has been completed, we directly get the results. If the asynchronous task is not yet complete, so get () will block until the task is complete before returning the results.
* ************************************************* **
* a future <V> interface represents the result of a future that may be returned, it defines the method are:
* gET (): Getting results (may wait)
* gET (Long timeout, TimeUnit Unit): get results, but just waiting for a specified time;
* the cancel (boolean mayInterruptIfRunning): cancel the current task;
* isDone (): determine whether the task has been completed.
* /
Class TestFuture {

public static void main (String [] args) {
Executor = Executors.newFixedThreadPool ExecutorService (. 4);
// define the task
a Callable <String> new new Task = a Callable <String> () {

@Override
public String Call () throws Exception {
return "Callable Interface";
}
};
// Submit tasks and obtains Future:
Future <String> = executor.submit Future (task);

the try {
// Get asynchronous execution result returned from the Future:
String = Future.get result (); // may be blocked
System.out.println ( Result);
} the catch (InterruptedException E) {
e.printStackTrace ();
} the catch (ExecutionException E) {
e.printStackTrace ();
}
}

}

Guess you like

Origin www.cnblogs.com/wueryuan/p/12073064.html