A Preliminary Exploration of Thread Pool

The basic idea of ​​thread pool

  • Thread pooling is a form of multithreading where tasks are added to a queue during processing, and then automatically started after threads are created.
  • Open up an area in the system to store some standby threads, and this area becomes the thread pool.
  • If there is a task to be executed, a standby thread is borrowed from the thread pool to execute the specified task, and the borrowed thread is returned after the task execution ends, thus avoiding the problem of creating a large number of thread objects and wasting CPU and memory resources.

Reasonable use of thread pools can bring three benefits

  • First: reduce resource consumption. Reduce the cost of thread creation and destruction by reusing already created threads.
  • Second: improve the response speed. When a task arrives, the task can execute immediately without waiting until the thread is created.
  • Third: improve the manageability of threads. Threads are scarce resources. If they are created without restrictions, it will not only consume system resources, but also reduce the stability of the system. Using thread pools can be used for unified allocation, tuning, and monitoring.

Common thread pool

  1. newSingleThreadExecutor()
    A thread pool of a single thread, that is, only one thread in the thread pool works at a time, and a single thread executes tasks serially
  2. newFixedThreadPool(int nThreads)
    A fixed number of thread pools, each submitted task is a thread until the maximum number of thread pools is reached, and then it enters the waiting queue and continues to execute until the previous task is completed.
  3. newCachedThreadPool() [recommended]
    The thread pool can be cached. When the size of the thread pool exceeds the threads required to process the task, some idle threads (usually no execution for 60 seconds) will be recycled. When there is a task, it will be smart to add a new thread to execute.
  4. newScheduledThreadPool(int corePoolSize)
    Unlimited thread pool, supports timing and periodic execution threads
    Delayed thread pool, Queue queue uses DelayedWorkQueue, which is a queue that can delay execution of blocking tasks

Create task thread class

class MyTask implements Runnable{
    private int count;
    private String taskName;
    public MyTask(String taskName, int count){
        this.count = count;
        this.taskName = taskName;
    }
    public void run(){
        System.out.println("\n"+Thread.currentThread().getName()+"开始执行任务"+taskName+">>");
        for(int i=0;i<count;i++){
            System.out.print(taskName+"-"+i+" ");
        }
        System.out.println("\n"+taskName+"任务执行结束。。");
    }
}

Single-task thread pool usage

public class Main{

    public static void main(String[] args){
         MyTask task1 = new MyTask("task1", 20);
         MyTask task2 = new MyTask("task2", 20);
         MyTask task3 = new MyTask("task3", 10);
         //创建单任务线程池
         ExecutorService singlePool = Executors.newSingleThreadExecutor();
         singlePool.execute(task1);
         singlePool.execute(task2);
         singlePool.execute(task3);
         //所有任务都结束后关闭线程池
         singlePool.shutdown();
    }
}

Fixed size thread pool

public class Main{

    public static void main(String[] args){
         MyTask task1 = new MyTask("task1", 50);
         MyTask task2 = new MyTask("task2", 50);
         MyTask task3 = new MyTask("task3", 30);
         //创建固定大小的线程池
         ExecutorService threadPool = Executors.newFixedThreadPool(2);
         threadPool.execute(task1);
         threadPool.execute(task2);
         threadPool.execute(task3);
         //所有任务都结束后关闭线程池
         threadPool.shutdown();
    }
}

Create a cacheable thread pool [recommended]

public static void main(String[] args){
     MyTask task1 = new MyTask("task1", 30);
     MyTask task2 = new MyTask("task2", 30);
     MyTask task3 = new MyTask("task3", 20);
     //创建大小可变的线程池
     ExecutorService threadPool = Executors.newCachedThreadPool();
     threadPool.execute(task1);
     threadPool.execute(task2);
     threadPool.execute(task3);
     //所有任务都结束后关闭线程池
     threadPool.shutdown();
}

Create a deferred thread pool

public static void main(String[] args){
     MyTask task1 = new MyTask("task1", 30);
     MyTask task2 = new MyTask("task2", 30);
     MyTask task3 = new MyTask("task3", 20);
     //创建有时延的线程池
     ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(2);
     //创建单线程延时线程池
     ScheduledExecutorService singleThreadPool = Executors.newSingleThreadScheduledExecutor();

     threadPool.schedule(task1, 1, TimeUnit.SECONDS);
     threadPool.schedule(task2, 1500, TimeUnit.MILLISECONDS);
     singleThreadPool.schedule(task3, 2000, TimeUnit.MILLISECONDS);

     //所有任务都结束后关闭线程池
     threadPool.shutdown();
     singleThreadPool.shutdown();
}

Thread pool for custom parameters

Use the java.util.concurrent.ThreadPoolExecutor class (which implements ExecutorService) to implement a custom thread pool. When a new task arrives, it will be processed according to the following rules:

1) If the number of threads in the current thread pool is less than the specified standard value, It tends to create threads;

2) If the number of threads in the current thread pool is more than the specified standard value, it tends to put new tasks in the queue; if the queue is full and the number of threads does not exceed the maximum value, a new task is created. thread.

3) If the number of threads in the current thread pool has reached the maximum value and the queue is full, the request is rejected.

4) If the idle thread exceeds the preset survival time, the idle thread object will be destroyed.

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue)

Some common methods of the ThreadPoolExecutor class:

public int getCorePoolSize() Get the standard size of the thread pool

public int getActiveCount() Return the number of threads executing tasks in the thread pool

public int getPoolSize() Get the current size of the thread pool

public int getMaximumPoolSize() Get The maximum size of the thread pool

public BlockingQueue getQueue() Returns the work waiting queue of the thread pool

public static void main(String[] args){
       MyTask task1 = new MyTask("task1", 30);
        MyTask task2 = new MyTask("task2", 30);
        MyTask task3 = new MyTask("task3", 20);
        MyTask task4 = new MyTask("task4", 20);
        //创建工作等待队列
        BlockingQueue workQueue = new ArrayBlockingQueue(3);
        //创建自定义线程池
        ThreadPoolExecutor myThreadPool = new ThreadPoolExecutor(
             2, 4, 100, TimeUnit.SECONDS, workQueue);
        myThreadPool.execute(task1);
        myThreadPool.execute(task2);
        myThreadPool.execute(task3);
        myThreadPool.execute(task4);
        //所有任务都结束后关闭线程池
        myThreadPool.shutdown();
}

Reference documents:
1. https://blog.csdn.net/qq_26608277/article/details/70741622
2. http://ifeve.com/java-threadpool/

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325478474&siteId=291194637