11. The thread pool

  • A fourth way to get threads: a thread pool, an ExecutorService that uses one of several possible pool threads to execute each submitted task, usually configured using the Execorate Factory method.

  • Thread pools solve two different problems: they typically provide increased performance when performing a large number of asynchronous tasks because of the reduced overhead per task invocation, and they also provide a way to bind and manage resources, including the threads used when executing the task set. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of tasks completed.

  • For ease of use across a large number of contexts, this class provides many tunable parameters and extension hooks. However, programmers are strongly recommended to use the more convenient Executors factory method:

    • Executors. NewCachedThreadPool () (unbounded thread pool, can automatically threads recycling)

    • Executors. NewFixedThreadPool (int) (fixed size thread pool)

    • Executors. NewSingleThreadExecutor () (single background thread)

    They all have predefined Settings for most usage scenarios

/* * thread pool: provides a thread queue, which holds all the threads in the waiting state. It avoids the extra overhead of creation and destruction and improves the response speed. * * 2, the thread pool architecture: * Java. Util. Concurrent. The Executor: responsible for the use of threads and scheduling the root of the interface * | - * * ExecutorService interface: The main interface * | thread pool - ThreadPoolExecutor thread pool implementation class interface: * | - ScheduledExecutorService son in charge of thread scheduling * | - ScheduledThreadPoolExecutor: Inherit ThreadPoolExecutor and implement ScheduledExecutorService */
 
 public class TestThreadPool {

    public static void main(String[] args) {
        Create a thread pool
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("thread-call-runner-%d").build();
        /** * corePoolSize: the maximum number of core threads in a thread pool ** maximumPoolSize: the maximum number of threads in a thread pool ** keepAliveTime: the lifetime of an idle thread. * * TimeUnitunit: the unit of keepAliveTime. * * workQueue: a blocking queue for caching tasks * * ThreadFactory: specifies the factory to create the thread */
        ExecutorService pool =
                new ThreadPoolExecutor(10.20.200L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(),namedThreadFactory);

        ThreadPoolDemo demo = new ThreadPoolDemo();

        //2. Assign tasks to threads in the thread pool
        for (int i = 0; i < 10; i++) {
            pool.submit(demo);
        }

        //3. Close the threadpool.shutdown(); }}class ThreadPoolDemo implements Runnable {

    private int i = 0;

    @Override
    public void run(a) {
        while(i <= 100){
            System.out.println(Thread.currentThread().getName() + ":"+ i++); }}}Copy the code