I. Structure
Located in the java. util. concurrent package. Declared as: public interfaceExecutor
All known sub-interfaces: ExecutorService, ScheduledExecutorService all known implementation classes: AbstractExecutorService, ScheduledThreadPoolExecutor, ThreadPoolExecutor II. Overview:
Execute submittedRunnableTask object. This interface provides a way to separate job submission from how each job runs (including details about thread usage and scheduling. GenerallyExecutorInstead of explicitly creating a thread. For example, you may use the following method instead of calling each task in a group of tasks.New Thread (new (RunnableTask (). start ():
Executor executor = anExecutor; executor.execute(new RunnableTask1()); executor.execute(new RunnableTask2()); ...
However,ExecutorThe interface does not strictly require that the execution be asynchronous. In the simplest case, the execution program can immediately run the submitted task in the caller's thread:
class DirectExecutor implements Executor { public void execute(Runnable r) { r.run(); } }
More often, tasks are executed in a thread that is not the caller's thread. The following execution program generates a new thread for each task.
class ThreadPerTaskExecutor implements Executor { public void execute(Runnable r) { new Thread(r).start(); } }
ManyExecutorThe implementation imposes some restrictions on the way and time of scheduling tasks. The following execution programs keep the task submission in sequence with the second execution program, which shows a composite execution program.
class SerialExecutor implements Executor { final Queue
tasks = new ArrayDeque
(); final Executor executor; Runnable active; SerialExecutor(Executor executor) { this.executor = executor; } public synchronized void execute(final Runnable r) { tasks.offer(new Runnable() { public void run() { try { r.run(); } finally { scheduleNext(); } } }); if (active == null) { scheduleNext(); } } protected synchronized void scheduleNext() { if ((active = tasks.poll()) != null) { executor.execute(active); } } }
TheExecutorImplementedExecutorService, Which is a more widely used interface.ThreadPoolExecutorClass provides an extensible thread pool implementation.ExecutorsClass provides convenient factory methods for these executors.
Memory consistency effect: the thread willRunnableObject submittedExecutorPrevious operationsHappen-beforeThe execution starts (possibly in another thread ).
Iii. Detailed method:
VoidExecute(Runnable command)
Execute a given command at a certain time in the future. This command may be executed in a new thread, a thread in the pool, or a calling thread.ExecutorImplementation decisions.
Parameters:command-Runable tasks
Throw:RejectedExecutionException-If the task cannot be executed.
NullPointerException-If the command is null