Java☞ thread pool

java.util.concurrent.Executors class
java.util.concurrent.Executor interfaces
both very similar, but create a thread pool, then all the way through implementation of the interface, multi-threading technology to solve major problems within the processor unit multiple threads of execution, it can significantly reduce the idle time of the processor unit, the processor unit to increase throughput.
Suppose a server time needed to complete a task are: T1 create a thread time, T2 time to perform tasks in the thread, T3 destroy threads time.
If: T1 + T3 is much greater than T2, then the thread pool should be used for improving the performance of the server.
A thread pool consists of four basic components:

  1. Thread Pool Manager (ThreadPoll): used to create and manage the thread pool, including creating a thread pool, the destruction of the thread pool, add a task;
  2. Worker thread (PoolWorker): threads in the pool, in a wait state in the absence of the task, the mission can be recycled;
  3. Task Interface (Task): Each task must implement in order to provide an execution thread scheduling tasks, it is mainly the task of the provisions of the entrance, after finishing the task execution, the execution state of the task and so on;
  4. Task queue (taskQueue): for storing task is not processed, provides a buffering mechanism.
    Thread pool is the focus on how to shorten or adjust T1, T3 technology time, thereby improving the performance of the server program.

Common thread pool

  1. newSingleThreadExecutor
    single thread pool thread, that thread pool that only one thread work, serial single-threaded tasks
  2. newFixedThreadExecutor (n)
    a fixed number of thread pools, each submit a task is a thread until it reaches the maximum number of threads in the pool, then back into the front of the queue until the task is complete before continuing execution
  3. newCacheThreadExecutor (recommended) [unbounded thread pool, the thread can be automatically recovered]
    cacheable thread pool when the thread pool size exceeds the required processing task threads, it will idle recovery section (generally 60 seconds without execution) thread when there are tasks, but also smart to add a new thread to execute.
  4. newScheduleThreadExecutor
    unlimited size of the thread pool support of regular and periodic execution thread
    Why use a thread pool?
    Create threads and to destroy threads spending is relatively large, the time may be longer than the time to deal with business. Such frequent thread creation and destruction of threads, plus business worker threads consume system resources of time, it may lead to insufficient system resources.
    Thread pool effect (advantage)
    the role of the thread pool is to limit the number of execution threads in the system, according to the environment of the system, either automatically or manually set the number of threads, to achieve the best operating results; less waste of system resources, resulting in more system is congested and inefficient. With a thread pool controls the number of threads, other threads waiting in line. Task a task is completed, and then taken from the top of the queue started. If there is no queue waiting process, the thread pool resources in a wait. When a new task needs to run, if there is a thread pool worker threads to wait, you can start running; otherwise enter the queue.
    1, to improve the efficiency created a certain number of threads in the pool, and so need to use the time to get from a pool this time than needed to create a thread object much faster. (Reducing the number of creation and destruction of threads)
    2, to facilitate the management can write a thread pool thread management code for the same pool of management, for example, there is the program to create 100 threads at startup, whenever there is a request, the allocation a thread go to work, if there are 101 concurrent requests just that extra that a request can wait in line, to avoid the creation of endless threads lead to a system crash.

Several commonly used to receive the thread pool object class or interface
E xecutorService is the real thread pool interface, usually thread pool objects created we generally use it receives.

public interface ExecutorService extends Executor {}

S cheduledExecutorService ExecutorService interface extends the interface, which is used to solve problems that require duplication of tasks to perform.

public interface ScheduledExecutorService extends ExecutorService {}

Class ThreadPoolExecutor is the default implementation class ExecutorService interface.

public class ThreadPoolExecutor extends AbstractExecutorService {}

Class ScheduledThreadPoolExecutor ThreadPoolExecutor inherited class, and implements ScheduledExecutorService interface, such methods can be performed periodically scheduled.

public class ScheduledThreadPoolExecutor
        extends ThreadPoolExecutor
        implements ScheduledExecutorService {}

Method of creating a common thread pool source as follows

package cn.ihep.threadPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

/**
 * 常见线程池创建
 * 
 * @author xiaoming
 *
 */
public class ThreadPoolTest {

    class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName());
        }
    }

    @Test
    public void singleThreadExcutor() {
        // 创建单线程池
        ExecutorService pool = Executors.newSingleThreadExecutor();
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
        MyThread t3 = new MyThread();
        MyThread t4 = new MyThread();
        pool.execute(t1);
        pool.execute(t2);
        pool.execute(t3);
        pool.execute(t4);

        // 关闭线程池
        pool.shutdown();
    }
--------------
输出:
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
---------------

    @Test
    public void fixedThreadExecutor() {
        int capacity = 10;
        ExecutorService pool = Executors.newFixedThreadPool(capacity);
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
        MyThread t3 = new MyThread();
        MyThread t4 = new MyThread();

        // 将线程放入线程池执行
        pool.execute(t1);
        pool.execute(t2);
        pool.execute(t3);
        pool.execute(t4);

        // 关闭线程池
        pool.shutdown();
    }
-------------------
输出结果:
pool-1-thread-1
pool-1-thread-3
pool-1-thread-4
pool-1-thread-2
-------------------

    @Test
    public void cacheThreadExecutor() {
        ExecutorService pool = Executors.newCachedThreadPool();
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
        MyThread t3 = new MyThread();
        MyThread t4 = new MyThread();
        pool.execute(t1);
        pool.execute(t2);
        pool.execute(t3);
        pool.execute(t4);

        // 关闭线程池
        pool.shutdown();
    }
--------------------
输出结果:
pool-1-thread-1
pool-1-thread-3
pool-1-thread-4
pool-1-thread-2
--------------------

    //newScheduledThreadPool线程池的实现
    public static void main(String[] args) {
        int corePoolSize = 10;
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(corePoolSize);
        pool.scheduleAtFixedRate(new Runnable() {

            @Override
            public void run() {
                // 打印系统时间
                System.out.println("*****************");
            }
        }, 1000, 1000 * 5, TimeUnit.MILLISECONDS);

        pool.scheduleAtFixedRate(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                System.out.println(System.nanoTime());
            }
        }, 1000, 2000, TimeUnit.MILLISECONDS);
    }
---------------------------
输出结果:
*****************
302010811506149
302012811595099
302014811621613
*****************
302016811745346
302018811897303
*****************
302020810967599
... ...
---------------------------
}



Thread pool, which has several work queue

  1. ArrayBlockingQueue
    is an array-based structure bounded blocking queue This queue orders elements FIFO principle.
  2. LinkedBlockingQueue
    a blocking queue list based structure, a FIFO queue in this sorting element, usually higher than a certain ArrayBlockingQueue. Static factory method Executors.newFiexedThreadPool () uses this queue
  3. SynchronousQueue
    a blocking queue element is not stored. Each insert operation must wait until another thread calls the removal operation, or insert operation has been in a blocked state, throughput is usually higher than LinkedBlockingQueue, static factory method Executors.newCacheThreadPool use this queue
  4. PriorityBlockingQueue
    a priority queue has unlimited obstruction

Understand how bounded / unbounded queue

Bounded queue
1. Initial poolSize <corePoolSize, runnable tasks submitted, as will a new Thread parameter immediately executed directly.
2. When the number of tasks submitted more than corePoolSize, will be submitted to the current runable in a block queue.
3. After bounded queue is full, if poolSize <maximumPoolsize, will try a new Thread performed emergency treatment immediately perform the corresponding runnable tasks.
4. 3. If the process can not, it will go to the fourth step performs reject operation.
Unbounded queue
compared to the bounded queue until system resources are exhausted, or unbounded task queue if the task team into the failure does not exist. When a new job arrives, the system is less than the number of threads corePoolSize, the new thread to perform the task. After reaching corePoolSize, we will not continue to increase, if there are subsequent addition of new tasks, but there are no free thread resources, the task directly into the waiting queue. If the task of creating and processing speed is very different, unbounded queue will maintain rapid growth, until the exhaust system memory.

Reproduced in: https: //www.jianshu.com/p/b9fcde9e462e

Guess you like

Origin blog.csdn.net/weixin_34357267/article/details/91233949