Thread pool create thread

Definition: using pooling technology to manage and use ready-made technology is called thread pool
Advantages of thread pool
Generally speaking, thread pool has the following advantages:
(1) Reduce resource consumption. Reduce the consumption caused by thread creation and destruction by reusing the created threads.
(2) Improve response speed. When the task arrives, the task can be executed immediately without waiting for the thread to be created.
(3) Improve thread manageability. Threads are scarce resources. If they are created without restrictions, they will not only consume system resources, but also reduce the stability of the system. Using thread pool can carry out unified allocation, tuning and monitoring.

1. Create a fixed number of thread pools

public class demo45 {
    public static void main(String[] args) {

        //Fixed number of thread pools created
        ExecutorService service = Executors.newFixedThreadPool(10);

        for(int i =0;i<2;i++){
            //Perform tasks
            service.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("Thread name:" +Thread.currentThread().getName());
                    //The description is to use thread pool to create threads
                }
            });
        }

    }
}

The printed thread name is not main, which indicates that the thread is created through the thread pool

Here's a classic question
Ten threads have been created to perform two tasks. How many threads have the current program created?
A: start two threads and open jconsole to observe


You can see that only two threads are executing

Execution flow of thread pool
After getting a task, it will judge whether the number of threads in the current thread pool has reached the maximum value. If not, create a new thread to execute the task;

When a task arrives, the number of threads in the current thread pool is the maximum, and there are no idle threads. The current task will be placed in the task queue of the thread pool for execution

public class demo45_2 {
    public static void main(String[] args) {

        // Create a fixed number of thread pools
        ExecutorService service = Executors.newFixedThreadPool(1);
        // Define task
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("Thread Name:" +
                        Thread.currentThread().getName());
            }
        };
        // Perform tasks
        service.execute(runnable);
        service.execute(runnable);
        service.execute(runnable);
        service.execute(runnable);
        service.execute(runnable);
        service.execute(runnable);
        service.execute(runnable);
        service.execute(runnable);
        service.execute(runnable);
        service.execute(runnable);
    }
}


It can be seen that after one thread is created, the code is still executed 10 times, indicating that the task queue in the thread pool has played a role and completed 10 starts of the thread

Set the name and priority of the thread

To implement (an interface) through a thread factory

public class demo46 {
    public static void main(String[] args) {
        //Thread factory
        MyThreadFactory myThreadFactory = new MyThreadFactory();


        ExecutorService service = Executors.newFixedThreadPool(10,myThreadFactory);
        for(int i =0;i<10;i++){
            service.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("Thread name+" + Thread.currentThread().getName()+",
                    thread priority "+Thread.currentThread().getPriority());
                }
            });
        }
    }

    private static int count = 1;

    static class MyThreadFactory implements ThreadFactory {
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            //Set the naming of thread pool
//            thread.setName("myThreadPool-" + count);
//            count++;
            thread.setName("myThreadPool-" + count++);

            //Set the priority of thread pool
            thread.setPriority(10);
            return thread;
        }
    }
}


You can see that the thread name and thread priority can be customized

2. Create thread pool with cache

public class demo47 {
    public static void main(String[] args) {
        //Create thread pool with cache

        ExecutorService service = Executors.newCachedThreadPool();

        //Perform 10 tasks
        for (int i = 0; i <10 ; i++) {
            service.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("Thread name" + Thread.currentThread().getName());
                }
            });
        }
    }
}

Applicable scenarios, when there are a large number of short-term tasks

3. Create a thread pool that can execute scheduled tasks

1.service.scheduleWithFixedDelay

public class demo48 {
    public static void main(String[] args) {

        //Thread pool that can perform scheduled tasks
        ScheduledExecutorService service = Executors.newScheduledThreadPool(10);

        System.out.println("Before performing the task"+ new Date());
        //Perform tasks

        service.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                System.out.println("Perform tasks"+ new Date());
            }
        },1,3, TimeUnit.SECONDS);
    }
}

Pass 4 parameters

public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                                     long initialDelay,
                                                     long delay,
                                                     TimeUnit unit);

Parameter 1 task of thread pool
Parameter 2 how long does the scheduled task delay to start execution
Parameter 3 execution frequency of scheduled tasks
Parameter 4 time unit used with parameter 2 and parameter 3

2.service.schedule

public class demo49 {
    public static void main(String[] args) {
        //Thread pool 2 that can execute scheduled tasks
        ScheduledExecutorService service = Executors.newScheduledThreadPool(10);

        System.out.println("Before performing the task"+ new Date());
        //Perform tasks

        service.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("Perform tasks"+ new Date());
            }
        },3, TimeUnit.SECONDS);

    }
}

Pass 3 parameters
Parameter 1 task of thread pool
Parameter 2 execution frequency of scheduled tasks
Parameter 3 time unit used with parameter 2

schedule:
1. There is no time setting for delayed execution
2. A scheduled task can only be executed once

3.service.scheduleAtFixedRate

service.scheduleAtFixedRate: the start time is the start time of the previous task as the start time (fixed frequency, not disturbed by other methods)

scheduleWithFixedDelay: the task start time is the end time of the previous task execution as the start time (the time is not fixed, which is set according to the execution time of the task, and may be interfered by sleep and wait methods)

4. Create a single thread pool to execute scheduled tasks

public class demo51 {
    public static void main(String[] args) {

        //Create a single thread pool that performs scheduled tasks
        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

        service.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Perform tasks:" + new Date());
            }
        },1,3, TimeUnit.SECONDS);
    }
}


Topic: what is the meaning of a single thread pool?
Answer: 1 There is no need to create and destroy threads frequently
2. It can better allocate, manage and store tasks (task queue)

5. Create a thread pool for a single thread

public class demo52 {
    public static void main(String[] args) {
        //Thread pool for a single thread
        ExecutorService service = Executors.newSingleThreadExecutor();


        for (int i = 0; i < 10; i++) {
            service.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("Thread Name:" +
                            Thread.currentThread().getName());
                }
            });
        }

    }
}

Print only one thread name

6.(JDK 8 +) asynchronous thread pool according to the current working environment (number of CPU cores, number of tasks)


Execution ends

Synchronous execution process:
1.main calling thread pool
2. After thread pool execution
3. When the thread pool is closed, main will also be closed
Asynchronous execution process:
1.main call asynchronous thread pool
2. The asynchronous thread pool is executed in the background. For the main thread, the asynchronous thread pool has been executed. Close the main thread


Add code

//Wait for the execution of asynchronous thread pool to complete (according to the termination status of thread pool)
        while (!service.isTerminated()){
        }

Determine whether the thread terminates, and then execute the thread
When the number of executions is large, the number of threads with the maximum number of current CPU cores will be created

7. General setting of thread pool


Set virtual machine memory

Maximum operating memory 10m
10: Abbreviation for execution
m: memory
x: max
10m: Unit


The memory is set to 10m
If the execution of a task exceeds the specified memory, an exception will occur

Executors create thread pool:
1. The number of threads is uncontrollable (excessive thread switching and slow program execution)
2. The number of tasks is uncontrollable (the number of tasks is infinite Integer.MAX_VALUE). When the number of tasks is large, it will cause memory overflow exception (OOM)

Keywords: Java Multithreading

Added by stuworx on Thu, 10 Feb 2022 04:19:00 +0200