JDK1.5 introduced the Executor framework for the implementation of decoupling task submission and after implementation of defined tasks handed over to the thread pool.
Thread pool by java.util.concurrent package Executors create a thread pool class factory method.
--------------------------------------------------------------------------------
Create a reusable fixed number of threads the thread pool, with unbounded queue shared way to run these threads.
static public ExecutorService newFixedThreadPool (int nThreads) nThreads
- the number of threads in the pool
ExecutorService pool = Executors.newFixedThreadPool(6);
Creates an Executor that uses a single worker thread to unbounded queue ways to run this thread.
static public ExecutorService newSingleThreadExecutor ()
ExecutorService threadPool = Executors.newSingleThreadExecutor();
Create a schedule in a given delay run command or to execute periodically has three threads of the thread pool.
The initial delay is 6 seconds, the interval timer is a timer task 2 seconds.
Executors.newScheduledThreadPool(3).scheduleAtFixedRate( ()-> {
System.out.println("bombing!");
}, 6, 2, TimeUnit.SECONDS);
}
Creates an Executor that uses a single worker thread to unbounded queue to run this thread.
static public ExecutorService newSingleThreadExecutor ()
--------------------------------------------------------------------------------
Thread pool framework provides two ways to submit the task, choose different ways according to different business needs.
① Executor.execute()
void execute(Runnable command)
Executes the given command at some future time. This command may have been pooled thread or threads are called in to perform in the new thread, which by the Executor implementation decisions.
② ExecutorService.submit()
|
submit(Callable<T> task) Submit a return value of the task for execution and returns a pending task represents a junction Future. |
|
Future <?> |
submit(Runnable task) Submits a Runnable task for execution and returns a Future representing that task. |
|
|
submit(Runnable task, T result) Submits a Runnable task for execution and returns a Future representing that task. |
Both methods can be submitted to the thread pool task, return type execute () method is void, it is defined in the Executor interface,
And submit () method returns the calculation result held Future object, which is defined in the interface ExecutorService
https://www.jianshu.com/p/87bff5cc8d8c
Depth analysis Executor framework ↓↓↓