preface

  • You should be familiar with multithreading. But what do you know about thread pools?
  • Today, I’m going to teach you everything you need to know about thread pools.

directory


1. Introduction


2. Working principle

2.1 Core Parameters

  • There are six core parameters in the thread pool, as follows

  • The configuration of the above six parameters determines the function of the thread pool. The specific setting timing = is passed in when the thread pool class object is created
  1. ThreadPoolExecutorClass = the actual implementation class of the thread pool
  2. Developers can customize thread pools by configuring core parameters according to different requirements
Executor Executor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory ); Public ThreadPoolExecutor (int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable workQueue>, ThreadFactory threadFactory )Copy the code

Note: There are four common thread pools built into Java (that is, with core parameters configured), as described below

2.2 Internal Principles and logic

When the thread pool is running, follow the following working logic


3. Use the process

The process for using a thread pool is as follows

Create a thread pool. // Create a thread pool by setting the parameters of the thread pool. ThreadPoolExecutor threadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory ); // Note: In Java, there are four common thread pools built in, which are described below. Submit tasks to the threadPool: execute() // description: pass the Runnable object threadpool.execute (new)Runnable() {
            @Override
            public void run() {... // Thread executes task}}); Shutdown () threadpool.shutdown (); A. Traverse all worker threads in the thread pool // b. Threadpool.shutdownnow () threadPool.shutdownNow () threadPool.shutdownNow () // shutdownNow: Set the state of the thread pool to STOP, then try to STOP all threads that are executing or suspending tasks and return to the list of waiting tasks. Call shutdown () to shutdown the thread pool; Call shutdownNow () if the task doesn't have to completeCopy the code

4. Common class 4 functional thread pools

Depending on the configuration of the parameters, the most common thread pools in Java are of four types:

  • Fixed-length thread pool (FixedThreadPool)
  • Timed thread pool (ScheduledThreadPool )
  • Cacheable thread pool (CachedThreadPool)
  • Single threaded thread pool (SingleThreadExecutor)

That is, Java has configured core parameters for the preceding four thread pools based on application scenarios

4.1 Fixed Length ThreadPool (FixedThreadPool)

  • Features: Only core threads & will not be collected, the number of threads is fixed, the task queue has no size limit (the exceeded thread task will wait in the queue)
  • Application scenario: Controls the maximum number of concurrent threads
  • Specific usage: PassExecutors.newFixedThreadPool()create
  • Example:
/ / 1. Create a fixed-length thread pool object & set the thread pool thread count fixed for 3 ExecutorService fixedThreadPool = Executors. NewFixedThreadPool (3); // 2. Create a Runnable thread object & Runnable task =newRunnable(){
  public void run(){
    System.out.println("On a mission."); }}; Execute () fixedThreadPool.execute(task); // 4. Close the thread pool fixedThreadPool.shutdown();Copy the code

4.2 ScheduledThreadPool (ScheduledThreadPool)

  • Features: fixed number of core threads, unlimited number of non-core threads (immediately recycled when idle)
  • Application scenario: Perform scheduled or periodic tasks
  • Use: by * Executors newScheduledThreadPool () * to create
  • Example:
/ / 1. Create a thread pool regularly object & set the thread pool thread fixed number of 5 ScheduledExecutorService scheduledThreadPool = Executors. NewScheduledThreadPool (5); // 2. Create a Runnable thread object & Runnable task =newRunnable(){
       public void run(){
              System.out.println("On a mission."); }}; / / 3. Submit to the thread pool tasks: the schedule () scheduledThreadPool. The schedule (task, 1, TimeUnit. SECONDS); . / / delay after 1 s mission scheduledThreadPool scheduleAtFixedRate (task, 10100, TimeUnit. MILLISECONDS); / / delay, every 1000 ms after 10 ms mission / / 4. Close the thread pool scheduledThreadPool. The shutdown ();Copy the code

4.3 Cacheable ThreadPool

  • Features: only non-core threads, the number of threads is not fixed (can be infinitely large), flexible recovery of idle threads (with timeout mechanism, almost no system resources when all recovered), new threads (when no threads available)

Any threaded tasks are executed as soon as they arrive, without waiting

  • Application scenario: Execute a large number of thread tasks with low time consumption
  • Use: by * Executors newCachedThreadPool * create ()
  • Example:
/ / 1. Create a cached thread pool object ExecutorService cachedThreadPool = Executors. NewCachedThreadPool (); // 2. Create a Runnable thread object & Runnable task =newRunnable(){
  public void run(){
        System.out.println("On a mission."); }}; Execute () cachedThreadPool.execute(task); / / 4. Close the thread pool cachedThreadPool. Shutdown (); // When the second task is executed, the first task has already completed // the thread that executed the first task is reused instead of creating a new thread each time.Copy the code

4.4 Single Threaded Thread Pool (SingleThreadExecutor)

  • Features: Only one core thread (ensures that all tasks are executed in a single thread in the specified order, without dealing with thread synchronization)

  • Application scenario: Operations that are not suitable for concurrent operations but may cause I/O block and affect UI thread response, such as database operations and file operations

  • Use: by * Executors newSingleThreadExecutor () * to create

  • Example:

/ / 1. Create a single threaded thread pool ExecutorService singleThreadExecutor = Executors. NewSingleThreadExecutor (); // 2. Create a Runnable thread object & Runnable task =newRunnable(){
  public void run(){
        System.out.println("On a mission."); }}; / / 3. Submit to the thread pool tasks: the execute () singleThreadExecutor. Execute (task); / / 4. Close the thread pool singleThreadExecutor. Shutdown ();Copy the code

4.5 Common Thread Pools Summary & Comparison


5. To summarize

  • After reading this article, I’m sure you have a good understanding of thread pooling & usage
  • And I’m going to continue with thatAndroidThe development of multithreading knowledge, specifically includingThreadClass,Handler,HandlerThreadWait, if you’re interested, you can continue to followCarson_Ho android Development Notes

Thumb up, please! Because your encouragement is the biggest power that I write!


Welcome to follow Carson_ho on wechat