Runable, Callable, Future, FutureTask, ExecutorService, Excetor, Excutors, and ThreadPoolExcetor in Java summarizes these keywords and their usage.
First classify them:
Runable, Callable
Future, FutureTask
ExecutorService,Excetor,Excutors,ThreadPoolExcetor
1. About Ranable and Callable
First of all, there are three ways to create threads in Java:
Advantages and disadvantages of three implementations:
Because of inheriting Thread, other classes cannot be inherited, and the current thread this can be obtained.
Implement the Runable interface, no return value, get the current thread Thread.currentThread()
Implement the Callable interface, you can get the return value through Future.get() and get the current thread Thread.currentThread()
Inheriting Thread, two steps:
class DemoThread extends Thread { @Override public void run() { super.run(); // Perform time-consuming operation... }}DemoThread t = new DemoThread();t.start();To implement Runable, generally use as follows:
new Thread(new Runnable() { @Override public void run() { // do something }}).start();For simplicity.
It is quite troublesome to obtain the results of thread execution in the above two methods and cannot be obtained directly. JDK1.5 adds Callable, Callable's call() method to return values and throw exceptions. Callable can return a Future object loaded with the calculation results.
Callable source code:
public interface Callable<V> { V call() throws Exception;}Basic usage of Callable:
FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() { @Override public Integer call() throws Exception { // do something return null; }});Thread thread = new Thread(futureTask);thread.start();Integer result = futureTask.get();Running the Callable task can get a Future object and get the return value executed by the thread through the get() method of Future. Then... Future,
What is the difference between FutureTask and how to use it?
->next()
2. About Future and FutureTask
In order to get the execution results of the thread, Future's FutureTask was introduced. So what is their relationship and how to use it?
The Future class is located under the java.util.concurrent package, which is an interface:
public interface Future<V> { boolean cancel(boolean mayInterruptIfRunning); boolean isCancelled(); boolean isDone(); V get() throws InterruptedException, ExecutionException; V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;}Future defines 5 methods:
1) boolean cancel(boolean mayInterruptIfRunning): Attempt to cancel the execution of this task. If the task has been completed, or has been cancelled, or cannot be cancelled for some other reason, this attempt will fail. When cancel() is called, if the call is successful and the task has not been started, the task will never run. If the task has been started, the mayInterruptIfRunning parameter determines whether the thread that executes the task should be interrupted in a way that attempts to stop the task. After this method returns, subsequent calls to isDone() will always return true. If this method returns true, subsequent calls to isCancelled() will always return true.
2) boolean isCancelled(): Return true if the task is cancelled before it completes normally.
3) boolean isDone(): Return true if the task has been completed. This may be done due to normal termination, exception or cancellation, in all these cases, this method will return true.
4) V get() throws InterruptedException,ExecutionException: If necessary, wait for the calculation to be completed and then get its result.
5) V get(long timeout,TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException: If necessary, wait at most after the given time to make the calculation complete, and get the result (if the result is available).
In general, Future provides three functions:
Determine whether the task is completed;
Ability to interrupt tasks;
Able to obtain task execution results.
Key points:
RunnableFuture inherits the Runnable interface and the Future interface, while FutureTask implements the RunnableFuture interface.
FutureTask implementation:
public class FutureTask<V> implements RunnableFuture<V>
Implementation of RunnableFuture interface:
public interface RunnableFuture<V> extends Runnable, Future<V> { void run();}FutureTask is a unique implementation class of the Future interface.
In addition to wrapping FutureTask with Thread, there is another way to use it:
ExecutorService executor = Executors.newCachedThreadPool();FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() { @Override public Integer call() throws Exception { // do something return null; }});executor.submit(futureTask);Integer result = futureTask.get(); The Executor framework is used here.
->next();
3. About ExecutorService,Excetor,Excutors,ThreadPoolExcetor
The Executor framework was introduced in Java 5. The Executor framework is a framework that executes asynchronous tasks that execute policy calls, schedules, executes and controls.
Before talking about the Executor framework, we need to introduce a new concept - ThreadPoolExecutor:
public ThreadPoolExecutor(intcorePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
ThreadPoolExecutor is the underlying implementation of the Executors class.
In the JDK help documentation, there is a passage:
"It is strongly recommended that programmers use the more convenient Executors factory methods Executors.newCachedThreadPool() (unbounded thread pool, which can perform automatic thread recycle), Executors.newFixedThreadPool(int) (fixed-size thread pool), and Executors.newSingleThreadExecutor() (single background thread), all of which are predefined for most usage scenarios."
So what are ExecutorService, Excetor, and Excutors?
Excetor is a core interface at the abstract level:
public interface Executor { void execute(Runnable command);}The ExecutorService interface extends the Executor interface and provides methods such as returning Future objects, terminating, closing thread pools, etc.
public interface ExecutorService extends Executor { void shutdown(); <T> Future<T> submit(Callable<T> task); <T> Future<T> submit(Runnable task, T result); <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException;}Executors is a tool class similar to Collections. Provides factory methods to create different types of thread pools, such as FixedThreadPool or CachedThreadPool.
public class Executors { public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); } public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }}The above is a compilation of Java multi-threaded keywords, so it won’t be messy.
The above is the implementation of multi-threaded keyword sorting in Java introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!