The example of this article tells the use of Executor interface in Java. Share it for everyone for your reference. The specifics are as follows:
1. Definition of Executor interface in Java
public interface executor {void execute (runnable commit);}
2. Create a thread pool by static factory methods belowexecutors:
a) NewfixedThreadPool: Create a long thread pool. After reaching the maximum number of threads, the number of threads no longer increases.
If a thread ends due to non -expected Exception, the thread pool will supplement a new thread.
b) NewcacheDhreadPool: Create a cacheable thread pool. When the length of the pool exceeds the processing requirements, you can recover the idle threads.
c) newsinglethreadPool: Create a single -threaded Executor.
d) NewsCheDuledhreadPool: Create a long -term thread pool, and supports time -period and periodic task execution.
Similar to Timer. However, Timer is based on absolute time, which is sensitive to changes in the system clock, while ScheduleDThreadPoolexecutor only supports relative time.
3. Compare the application summary of the Timer class
1) Timer is the only thread to perform all Timer tasks. If a task is out of time, it will cause other Timertask time to accurately problems.
2) If Timrtask throws out uncheck abnormalities, Timer will have an unpredictable behavior. Therefore, ScheduleDhReadpoolexecutor can completely replace Timer.
3) In order to solve the life cycle of execution services, the ExecutorService interface expands Executor. The thread pool will include 3 states: running, shutting down, terminated.
4. Callable and FUTURE
Because Runnable does not return the value and cannot be thrown out of the Checked abnormality, Callable is a better abstraction. (Callable <void> indicates the task of no return value).
Future describes the life cycle of the task, and provides related methods to obtain the results of the task, cancel the task, check the task to complete or cancel it.
5.CompltingService integrates the functions of Executor and BlockingQueue.
Its take and poll can block the completion of the task.
It is hoped that this article is helpful to everyone's Java program design.