This article describes the executor interface usage in Java. Share to everyone for your reference. Specifically as follows:
Definition of executor interface in 1.Java
Public interface Executor {
void execute (Runnable command);
}
2.Executors the following static factory method creates a thread pool:
A) Newfixedthreadpool: Create a fixed-length thread pool. When the maximum number of threads is reached, the number of threads is no longer increasing.
If a thread ends due to unintended exception, the thread pool complements a new thread.
b) Newcachedthreadpool: Create a cacheable pool of threads. Idle threads can be reclaimed when the pool length exceeds the processing requirements.
c) Newsinglethreadpool: Create a single-threaded executor.
d) Newscheduledthreadpool: Create a fixed-length thread pool, and support timed and periodic task execution.
Similar to a timer. However, the timer is based on absolute time and is sensitive to changes to the system clock, whereas Scheduledthreadpoolexecutor only supports relative time.
3. Comparison of Timer class application summary
1 timer is the creation of a unique thread to perform all the timer tasks. If a task times out, it can cause other timertask time accuracy problems.
2 if TimerTask throws a uncheck exception, the timer will produce unpredictable behavior. Therefore, Scheduledthreadpoolexecutor can completely replace the timer.
3 in order to solve the lifecycle problem of executing service, the Executorservice interface extends the executor. The thread pool will include 3 states: Running,shutting down,terminated.
4.Callable and future
Because Runnable does not return a value and cannot throw a checked exception, callable is a better abstraction. (Callable<void> represents a task that has no return value).
Future describes the lifecycle of a task and provides relevant methods for obtaining the results of a task, canceling a task, and checking whether a task is complete or canceled.
5.CompletionService integrates the functions of executor and blockingqueue.
Its take and poll can block the acquisition of completed tasks.
I hope this article will help you with your Java programming.