Java multi-thread series -- thread pool architecture of "JUC thread pool" 01

Source: Internet
Author: User

1. Executor it is the "Executor" interface, which is used to execute tasks. To be precise, Executor provides the execute () interface to execute the submitted Runnable task objects. Executor is designed to separate "task submission" from "how to run a task. It only contains one function interface: void execute (Runnable command) 2. ExecutorService inherits from Executor. It is the "Executor service" interface, which exists for the "Executor interface Executor" service. To be precise, ExecutorService provides the "submit method" for submitting a task to the Executor) "," Let the executor execute the task (invokeAll, invokeAny method) "interface, and so on. ExecutorService's function list copies code 1 // when a request is closed, times out, or the current thread is interrupted, whatever occurs first will cause blocking until all tasks are completed. 2 boolean awaitTermination (long timeout, TimeUnit unit) 3 // executes a given task. When all tasks are completed, the Future list of the task status and result is returned. 4 <T> List <Future <T> invokeAll (Collection <? Extends Callable <T> tasks) 5 // executes a given task. When all tasks are completed or expire (whichever occurs first ), returns the Future list of the task status and result. 6 <T> List <Future <T> invokeAll (Collection <? Extends Callable <T> tasks, long timeout, TimeUnit unit) 7 // run the given task. If a task has been successfully completed (that is, no exception is thrown ), returns the result. 8 <T> T invokeAny (Collection <? Extends Callable <T> tasks) 9 // executes a given task. If a task is successfully completed (that is, no exception is thrown) before the specified timeout period expires ), returns the result. 10 <T> T invokeAny (Collection <? Extends Callable <T> tasks, long timeout, TimeUnit unit) 11 // if the execution program is closed, true is returned. 12 boolean isShutdown () 13 // if all tasks have been completed after being disabled, true is returned. 14 boolean isTerminated () 15 // start a closed sequence to execute previously submitted tasks, but do not accept new tasks. 16 void shutdown () 17 // try to stop all active tasks in progress, pause the tasks waiting for processing, and return the list of tasks waiting for execution. 18 List <Runnable> shutdownNow () 19 // submit a returned task for execution and return a Future indicating the outstanding results of the task. 20 <T> Future <T> submit (Callable <T> task) 21 // submit a Runnable task for execution and return a Future indicating the task. 22 Future <?> Submit (Runnable task) 23 // submit a Runnable task for execution and return a Future indicating the task. 24 <T> Future <T> submit (Runnable task, T result) Copy code 3. AbstractExecutorService extends actexecutorservice is an abstract class that implements the ExecutorService interface. AbstractExecutorService provides default implementation for function interfaces in ExecutorService. The AbstractExecutorService function list is not repeated here because it has the same function list as ExecutorService. 4. ThreadPoolExecutor is a well-known "Thread Pool ". It inherits from the AbstractExecutorService abstract class. ThreadPoolExecutor function list copy code 1 // create a new ThreadPoolExecutor with the given initial parameters and default thread factory and rejected execution handler. 2 ThreadPoolExecutor (int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue <Runnable> workQueue) 3 // create a new ThreadPoolExecutor with the given initial parameters and default thread factory. 4 ThreadPoolExecutor (int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue <Runnable> workQueue, RejectedExecutionHandler handler) 5 // create a new ThreadPoolExecutor with the given initial parameters and the rejected execution handler by default. 6 ThreadPoolExecutor (int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue <Runnable> workQueue, ThreadFactory threadFactory) 7 // create a new ThreadPoolExecutor with the given initial parameter. 8 ThreadPoolExecutor (int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue <Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) 9 10 // The method called Based on the execution of the given Runnable. 11 protected void afterExecute (Runnable r, Throwable t) 12 // if no task arrives during the hold activity period, the new task is being replaced when it arrives (if needed ), set the policy to control whether the Core Thread is timed out or terminated. 13 void allowCoreThreadTimeOut (boolean value) 14 // if this pool allows the core thread to time out and terminate, if no task arrives within the keepAlive time, the new task is being replaced when it arrives (if needed ), returns true. 15 boolean allowsCoreThreadTimeOut () 16 // when a request is closed, times out, or the current thread is interrupted, whatever occurs first will cause blocking until all tasks are completed. 17 boolean awaitTermination (long timeout, TimeUnit unit) 18 // method called before the given Runnable in the execution of the given thread. 19 protected void beforeExecute (Thread t, Runnable r) 20 // execute a given task at a certain time in the future. 21 void execute (Runnable command) 22 // call shutdown when the program is no longer referenced. 23 protected void finalize () 24 // returns the approximate number of threads that actively execute tasks. 25 int getActiveCount () 26 // returns the total number of completed approximate tasks. 27 long getCompletedTaskCount () 28 // return the number of core threads. 29 int getCorePoolSize () 30 // The time for the returned thread to stay active. This is the value of the time when the thread that exceeds the core pool size can stay idle before termination. 31 long getKeepAliveTime (TimeUnit unit) 32 // returns the maximum number of threads that were once in the pool at the same time. 33 int getLargestPoolSize () 34 // returns the maximum number of threads allowed. 35 int getMaximumPoolSize () 36 // return the current number of threads in the pool. 37 int getPoolSize () 38 // return the task queue used by this executor. 39 BlockingQueue <Runnable> getQueue () 40 // return the current handler used for unexecuted tasks. 41 RejectedExecutionHandler getRejectedExecutionHandler () 42 // return the total number of approximate tasks planned to be executed. 43 long getTaskCount () 44 // return the thread factory used to create a new thread. 45 ThreadFactory getThreadFactory () 46 // if the execution program is closed, true is returned. 47 boolean isShutdown () 48 // if all tasks have been completed after being disabled, true is returned. 49 boolean isTerminated () 50 // if the execution program is being terminated after shutdown or shutdownNow but has not been completely terminated, true is returned. 51 boolean isTerminating () 52 // start all core threads and keep them idle. 53 int prestartAllCoreThreads () 54 // start the Core Thread and keep it idle. 55 boolean prestartCoreThread () 56 // try to remove all canceled Future tasks from the work queue. 57 void purge () 58 // remove this task from the internal queue of the execution Program (if any) so that it will not run if it has not started. 59 boolean remove (Runnable task) 60 // set the number of core threads. 61 void setCorePoolSize (int corePoolSize) 62 // sets the time limit for the thread to remain idle before termination. 63 void setKeepAliveTime (long time, TimeUnit unit) 64 // set the maximum number of threads allowed. 65 void setMaximumPoolSize (int maximumPoolSize) 66 // set a new handler for unexecuted tasks. 67 void setRejectedExecutionHandler (RejectedExecutionHandler handler) 68 // sets the thread factory used to create a new thread. 69 void setThreadFactory (ThreadFactory threadFactory) 70 // an ordered close is initiated in the order in which submitted tasks were executed, but new tasks are not accepted. 71 void shutdown () 72 // try to stop all the active execution tasks, pause the processing of the waiting tasks, and return the list of tasks awaiting execution. 73 List <Runnable> shutdownNow () 74 // method called when Executor is terminated. 75 protected void terminated () Copy Code 5. ScheduledExecutorService is an interface inherited from ExecutorService. It is equivalent to ExecutorService that provides the "latency" and "periodical execution" functions. ScheduledExecutorService provides function interfaces to schedule tasks to be executed after a given delay or during the task cycle. Copy code 1 from the ScheduledExecutorService function list // create and execute ScheduledFuture enabled after a given delay. 2 <V> ScheduledFuture <V> schedule (Callable <V> callable, long delay, TimeUnit unit) 3 // create and execute one-time operations enabled after a given delay. 4 ScheduledFuture <?> Schedule (Runnable command, long delay, TimeUnit unit) 5 // create and execute a scheduled operation that is enabled for the first time after a given initial delay. Subsequent operations have a given cycle; that is, the execution will start after initialDelay, and then after initialDelay + period, and then after initialDelay + 2 * period, and so on. 6 ScheduledFuture <?> ScheduleAtFixedRate (Runnable command, long initialDelay, long period, TimeUnit unit) 7 // create and execute a scheduled operation that is enabled for the first time after a given initial delay. Then, there is a given delay between each execution termination and the next execution start. 8 ScheduledFuture <?> ScheduleWithFixedDelay (Runnable command, long initialDelay, long delay, TimeUnit unit) Copies Code 6. ScheduledThreadPoolExecutor extends to ThreadPoolExecutor and implements the ScheduledExecutorService interface. It is equivalent to ScheduledExecutorService that provides the "latency" and "periodical execution" functions. ScheduledThreadPoolExecutor is similar to Timer, but in highly concurrent programs, ScheduledThreadPoolExecutor has better performance than Timer. Copy code 1 from the ScheduledThreadPoolExecutor function list // create a new ScheduledThreadPoolExecutor using the given core pool size. 2 ScheduledThreadPoolExecutor (int corePoolSize) 3 // use the given initial parameter to create a new ScheduledThreadPoolExecutor. 4 ScheduledThreadPoolExecutor (int corePoolSize, RejectedExecutionHandler handler) 5 // create a new ScheduledThreadPoolExecutor using the given initial parameters. 6 ScheduledThreadPoolExecutor (int corePoolSize, ThreadFactory threadFactory) 7 // use the given initial parameters to create a new ScheduledThreadPoolExecutor. 8 ScheduledThreadPoolExecutor (int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler) 9 // modify or replace the task used to execute callable. 11 protected <V> RunnableScheduledFuture <V> decorateTask (Callable <V> callable, RunnableScheduledFuture <V> task) 12 // modify or replace the task used to execute runnable. 13 protected <V> RunnableScheduledFuture <V> decorateTask (Runnable runnable, RunnableScheduledFuture <V> task) 14 // use the required zero-latency command. 15 void execute (Runnable command) 16 // gets the policy on whether to continue executing existing scheduled tasks when the program has been shut down. 17 boolean getContinueExistingPeriodicTasksAfterShutdownPolicy () 18 // gets the policy on whether to continue executing the existing delayed task when the program is shut down. 19 boolean getExecuteExistingDelayedTasksAfterShutdownPolicy () 20 // return the task queue used by this executor. 21 BlockingQueue <Runnable> getQueue () 22 // remove this task from the internal queue of the execution Program (if it exists), so that it will not run if it has not started yet. 23 boolean remove (Runnable task) 24 // create and execute ScheduledFuture enabled after a given delay. 25 <V> ScheduledFuture <V> schedule (Callable <V> callable, long delay, TimeUnit unit) 26 // create and execute one-time operations enabled after a given delay. 27 ScheduledFuture <?> Schedule (Runnable command, long delay, TimeUnit unit) 28 // create and execute a scheduled operation that is enabled for the first time after a given initial delay. Subsequent operations have a given cycle; that is, the execution will start after initialDelay, and then after initialDelay + period, and then after initialDelay + 2 * period, and so on. 29 ScheduledFuture <?> ScheduleAtFixedRate (Runnable command, long initialDelay, long period, TimeUnit unit) 30 // create and execute a scheduled operation that is enabled for the first time after a given initial delay. Then, there is a given delay between each execution termination and the next execution start. 31 ScheduledFuture <?> ScheduleWithFixedDelay (Runnable command, long initialDelay, long delay, TimeUnit unit) 32 // sets whether to continue executing existing scheduled tasks when the program is shut down. 33 void setContinueExistingPeriodicTasksAfterShutdownPolicy (boolean value) 34 // you can specify whether to continue executing an existing delayed task when the program is shut down. 35 void setExecuteExistingDelayedTasksAfterShutdownPolicy (boolean value) 36 // an ordered shutdown task is triggered during execution of a previously submitted task, but new tasks are not accepted. 37 void shutdown () 38 // try to stop all ongoing tasks, pause the processing of pending tasks, and return the list of pending tasks. 39 List <Runnable> shutdownNow () 40 // submit a returned task for execution and return a Future indicating the outstanding results of the task. 41 <T> Future <T> submit (Callable <T> task) 42 // submit a Runnable task for execution and return a Future indicating the task. 43 Future <?> Submit (Runnable task) 44 // submit a Runnable task for execution and return a Future indicating the task. 45 <T> Future <T> submit (Runnable task, T result) Copy code 7. Executors is a static factory class. It returns objects of the class ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable through the static factory method. Copy code 1 from the Executors function list. // return the Callable object. When you call it, you can run the operation with the given privilege and return the result. 2 static Callable <Object> callable (PrivilegedAction <?> Action) 3 // return the Callable object. When calling it, you can run the exception operation with the given privilege and return the result. 4 static Callable <Object> callable (PrivilegedExceptionAction <?> Action) 5 // return the Callable object. When calling it, you can run the given task and return null. 6 static Callable <Object> callable (Runnable task) 7 // return the Callable Object. When calling it, you can run the given task and return the given result. 8 static <T> Callable <T> callable (Runnable task, T result) 9 // return the default thread factory used to create a new thread. 10 static ThreadFactory defaultThreadFactory () 11 // create a thread pool where new threads can be created as needed, but they will be reused when previously constructed threads are available. 12 static ExecutorService newCachedThreadPool () 13 // create a thread pool where new threads can be created as needed, but they will be reused when previously constructed threads are available, and use the provided ThreadFactory to create a new thread as needed. 14 static ExecutorService newCachedThreadPool (ThreadFactory threadFactory) 15 // create a thread pool that can reuse the fixed number of threads and run these threads in a shared unbounded queue. 16 static ExecutorService newFixedThreadPool (int nThreads) 17 // create a thread pool that can reuse the fixed number of threads and run these threads in a shared unbounded queue, use the provided ThreadFactory to create a new thread as needed. 18 static ExecutorService newFixedThreadPool (int nThreads, ThreadFactory threadFactory) 19 // create a thread pool, which can be scheduled to run commands after a given delay or regularly run. 20 static ScheduledExecutorService newScheduledThreadPool (int corePoolSize) 21 // create a thread pool, which can be scheduled to run commands after a given delay or regularly run. 22 static ScheduledExecutorService newScheduledThreadPool (int corePoolSize, ThreadFactory threadFactory) 23 // create an Executor that uses a single worker thread and runs this thread in an unbounded queue mode. 24 static ExecutorService newSingleThreadExecutor () 25 // create an Executor that uses a single worker thread, run the thread in an unbounded queue mode, and create a new thread using the provided ThreadFactory when necessary. 26 static ExecutorService newSingleThreadExecutor (ThreadFactory threadFactory) 27 // create a single-threaded execution program that can be scheduled to run commands after a given delay or regularly run. 28 static ScheduledExecutorService newSingleThreadScheduledExecutor () 29 // create a single-thread execution program that can schedule command execution or regular execution after a given delay. 30 static ScheduledExecutorService newSingleThreadScheduledExecutor (ThreadFactory threadFactory) 31 // return the Callable object, which can be called to execute the specified callable object in the current access control context. 32 static <T> Callable <T> privilegedCallable (Callable <T> callable) 33 // return the Callable object, which can be called in the current access control context, use the current context class loader as the context class loader to execute the specified callable object. 34 static <T> Callable <T> privilegedCallableUsingCurrentClassLoader (Callable <T> callable) 35 // return the thread factory used to create a new thread. These new threads have the same permissions as the current thread. 36 static ThreadFactory privilegedThreadFactory () 37 // return an object that delegates all the defined ExecutorService methods to the specified execution program, but other methods may not be accessible using forced conversion. 38 static ExecutorService unmarshableexecutorservice (ExecutorService executor) 39 // return an object that delegates all the defined ExecutorService methods to the specified execution program, but other methods may not be accessible using forced conversions. 40 static ScheduledExecutorService unmarshablescheduledexecutorservice (ScheduledExecutorService executor): The sample code thread pool is copied. The following uses an example to demonstrate the use of the thread pool. Copy code 1 import java. util. concurrent. executors; 2 import java. util. concurrent. executorService; 3 4 public class ThreadPoolDemo1 {5 6 public static void main (String [] args) {7 // create a thread pool with a fixed number of reusable threads 8 ExecutorService pool = Executors. newFixedThreadPool (2); 9 // the Runnable interface object is created, and the Thread object also implements the Runnable interface 10 Thread ta = new MyThread (); 11 Thread tb = new MyThread (); 12 Thread tc = new MyThread (); 13 Thread Td = new MyThread (); 14 Thread te = new MyThread (); 15 // put the Thread into the pool for execution 16 pool.exe cute (ta); 17 pool.exe cute (tb ); 18 pool.exe cute (tc); 19 pool.exe cute (td); 20 pool.exe cute (te); 21 // closes the thread pool 22 pool. shutdown (); 23} 24} 25 26 class MyThread extends Thread {27 28 @ Override29 public void run () {30 System. out. println (Thread. currentThread (). getName () + "is running. "); 31} 32} copy the code running result: pool-1-thread-1 is running. pool -1-thread-2 is running. pool-1-thread-1 is running. pool-1-thread-2 is running. pool-1-thread-1 is running. result Description: A thread pool is created in the main thread. The thread pool capacity is 2. That is, the maximum number of threads in the thread pool can run at the same time. Then, add the three threads ta, tb, tc, td, and te to the thread pool for running. Finally, shut down the thread pool through shutdown.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.