Wechat search “Java fish”, a knowledge point every day not bad

All content and history will be updated on Github. Welcome star

(1) One knowledge point every day

What’s the difference between runnable and callable? What is FutureTask?

(2) Answer

2.1 Difference between Runnable and Callable

Both runnable and Callable can be used to write multithreaded programs. The difference between the two is that:

1. After the Runnable interface is implemented, no result information is returned. After the Callable interface is implemented, a return value is returned.

2. If runnable interface exceptions are implemented, throws exceptions cannot be passed. After the Callable interface is implemented, exceptions can be thrown directly

2.2 What is Future?

When implementing multithreading using the Callable interface, we use FutureTask to get the return value. What are Future and FutureTask?

FutureTask is an implementation class of the Future, which is an interface for retrieving asynchronous computations.

public interface Future<V> {
    boolean cancel(boolean mayInterruptIfRunning);
    boolean isCancelled(a);
    boolean isDone(a);
    V get(a) throws InterruptedException, ExecutionException;
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}
Copy the code

The source code for the Future interface is simple, and it implements five methods

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.

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

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

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.

To sum up, Future implements the following functions: it can interrupt ongoing tasks, determine whether the task is still being executed, and obtain the results after the task is executed. FutureTask is a common implementation class for Future interfaces