Thread pool in java

Keywords: Java

It's very simple to create threads when we're performing tasks.
But when there are many concurrent threads, and each thread executes a short time task, it is over. This frequent creation of threads greatly reduces the efficiency of the system, because creating and destroying threads takes time and cpu of the system.
In java, thread pools can be used to make threads reusable, that is to say, to complete a task, not destroy, but also to perform other tasks. The java.uitl.concurrent.ThreadPoolExecutor class is the core class in the thread pool, which provides four kinds of thread pools for us to use. The four methods are:
1. New CachedThreadPool creates a cacheable thread pool. If the length of the thread pool exceeds the processing requirement, it can flexibly reclaim idle threads. If it is not, it can create new threads.
2. New Fixed ThreadPool creates a fixed-length thread pool that controls the maximum number of concurrent threads, and the threads that exceed it will wait in the queue.
3. New Scheduled ThreadPool creates a fixed-length thread pool that supports both timing and periodic task execution.
4. New Single ThreadExecutor creates a single threaded thread pool, which only uses a single worker thread to perform tasks, ensuring that all tasks are executed in a specified order (FIFO, LIFO, priority).

Examples are given:

package com.zhangyike.threadPool;

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

/*
 * Thread pool
 */
public class ThreadPool01 {
    public static void main(String[] args) {
        singelThread();
    }

    //Fixed thread pool.
    public static void fixedThreadPool(){
        //Create a thread pool. There are three threads in the thread pool. These threads will not stop automatically. They are running all the time. If you want to stop them, you must manually.
        ExecutorService pool = Executors.newFixedThreadPool(3);

        //Ten tasks were thrown into the thread pool, but there were only three threads in the thread pool, and these 10 tasks were accomplished by the three threads.
        for (int j = 0; j < 10; j++) {
            final int task = j;
            //Put tasks into the thread pool
            pool.execute(new Runnable(){

                @Override
                public void run() {
                /*  try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }*/
                    for (int i = 0; i < 10; i++) {
                        //Accessing data from external classes in internal classes must be final modifiers
                        System.out.println(Thread.currentThread().getName() + ",is loop of i = " + i + ", for task of task = " + task);
                    }

                }
            });

        }
        //Complete all tasks, stop all threads
        pool.shutdown();
        //Each thread executes a task, and after execution, the thread dies automatically.
        pool.shutdownNow();
    }

    //Unfixed thread pool, when there are many tasks, the thread pool will automatically add threads to handle tasks.
    public static void unfixedThreadPool() {
        //Tasks are automatically added to threads
        ExecutorService pool = Executors.newCachedThreadPool();

        for (int i = 0; i < 10; i++) {
            final int task = i;

            pool.execute(new Runnable() {

                @Override
                public void run() {
                    for (int j = 0; j < 10; j++) {
                        System.out.println(Thread.currentThread().getName() + ", loop of j = " + j + ", excute task = " + task);
                    }
                }
            });
        }

        System.out.println("all task is finished!");
        pool.shutdown();
    }

    //A single thread ensures that there is only one thread in the thread pool. When the thread dies, it will find a thread to replace it.
    //This thread is dead and can live for him.
    public static void singelThread() {
        ExecutorService single = Executors.newSingleThreadExecutor();

        for (int i = 0; i < 10; i++) {
            final int task = i;
            single.execute(new Runnable() {

                @Override
                public void run() {
                    for (int j = 0; j < 10; j++) {
                        System.out.println(Thread.currentThread().getName() + ", loop of j = " + j + ", excute task = " + task);
                    }
                }
            });
        }
        System.out.println("all task is finished!");
        single.shutdown();
    }

//Timing thread pool
public static void timerThread(){           Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable(){

            @Override
            public void run() {
                System.out.println("boming...");

            }

        }, 10, 2, TimeUnit.SECONDS);//It runs for the first time after 10 seconds and every 2 seconds thereafter.

    }
}

Posted by ArizonaJohn on Thu, 11 Jul 2019 12:58:05 -0700