Callable

In Java, threads are created either by inheriting the Thread class or by implementing the Runnable interface. However, the disadvantage of both approaches is that the execution results cannot be obtained after the threaded task has finished executing. We generally can only use shared variables or shared storage and thread communication to achieve the purpose of obtaining task results.

However, Java also provides operations to retrieve the results of a task using Callable and Future. Callable is used to perform tasks and produce results, while Future is used to obtain results.

The Callable interface is defined as follows:

public interface Callable<V> { /** * Computes a result, or throws an exception if unable to do so. * * @return computed result * @throws Exception if unable to compute a result  */ V call() throws Exception; }Copy the code

Unlike the Runnable interface, the Call method has a generic return value V.

The Future model

The core of the Future pattern is to remove the wait time for main functions and make the time that would otherwise have to wait available for processing other business logic

Futrure mode: For multi-threading, if thread A wants to wait for the result of thread B, then thread A does not need to wait for the result of thread B. It can get A Future first, and then get the real result after the result of thread B.

An example often cited in multi-threading is: the download of network pictures, at the beginning of the blurred picture to replace the last picture, such as the download picture thread after downloading the picture in the replacement. And there are other things you can do along the way.

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; /** * @author wn: ExecutorService public class ThreadCallTest {public static void main(String[]args){ExecutorService executor=Executors.newCachedThreadPool(); Task task=new Task(); Future<Integer> result=executor.submit(task); if (executor ! = null) executor.shutdown(); try { System.out.println("call result"+result.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } System.out.println("over"); } } class Task implements Callable<Integer>{ @Override public Integer call() throws Exception { System.out.println("3. Start..." ); Thread.sleep(3000); 4 System. Out.println (" end..." ); return "xyz"; }}Copy the code

Result.get () will wait 3 seconds and return xyz if the Task starts without affecting the main thread

Future common methods

V get() : Gets the result of the asynchronous execution. If no result is available, this method blocks until the asynchronous calculation is complete.

V GET (Long timeout, TimeUnit Unit) : Gets the result of asynchronous execution. If no result is available, this method will block, but there is a time limit. If the blocking time exceeds the specified timeout period, this method will throw an exception.

Boolean isDone() : Returns true if the task is finished, whether it was canceled or an exception occurred. => result.isDone()

Boolean isCanceller() : Returns true if the task is canceled before completion.

Boolean Cancel (Boolean mayInterruptRunning) : Perform cancel(…) if the task has not yet started. Method will return false; If the task has already started, executing the cancel(true) method attempts to stop the task by interrupting the thread executing the task, and returns true on success;

When the task has been started, executing the cancel(false) method will not affect the thread of the executing task (allowing the thread to execute until completion), and returns false;

When the task is complete, cancel(…) Method will return false. The mayInterruptRunning parameter indicates whether the executing thread is interrupted.

In fact, the Future provides three functions:

  • (1) Can interrupt the execution of the task
  • (2) Determine whether the task is completed
  • (3) Obtain the result after the task is executed

Personal blog Snail