23. How to set the maximum number of core threads in the thread pool (cpu-intensive, IO-intensive)

How to set the maximum number of core threads in the thread pool (cpu-intensive, IO-intensive)

 

Concurrent programming: (concurrent/parallel)

Concurrency: Multiple threads operate on the same resource

Parallelism: multiple threads run together (thread pool can be realized) parallelism is the most efficient

Question: How do we set this maximum number of core threads?

 

Idea 1, CPU-intensive: According to the number of cores of the CPU (the number of cores is defined as a few), the efficiency of the CPU can be kept at the highest level!

How to get the number of cpu cores:

Method 1. Check our task manager, check performance, cpu (12 cores)

 

Method 2. Open the computer management, check the device manager, and count how many processors there are (12)

 

! ! ! Method 3. We’d better not write it to death. If the operation and maintenance runs the server, the number of cores of the server must be more than ours, so we use java Api to get it (Runtime.getRuntime().availableProcessors()), so here we replace Down.

 

Idea 2, IO-intensive: Determine the threads that consume a lot of IO in our program. (As long as it is greater than this number, it is ok)

 

package org.example.threadpoolexecutor;



import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;



public class TestThreadPoolExecutorThere {

    public static void main(String[] args) {

//        ExecutorService threadPool = Executors.newSingleThreadExecutor();//单个线程的线程池

//        ExecutorService threadPool = Executors.newFixedThreadPool(5);//设定固定线程个数的线程池

        ExecutorService threadPool = Executors.newCachedThreadPool();//可以随着使用的线程个数变化而而变化的线程池

        try {

            for (int i = 1; i <=100 ; i++) {

                    threadPool.execute(()->{

                        System.out.println(Thread.currentThread().getName()+"=>ok");

                    });

            }

        } catch (Exception e) {

            throw new RuntimeException(e);

        } finally {

            threadPool.shutdown();

        }

    }

}





Supongo que te gusta

Origin blog.csdn.net/logtcm4/article/details/127886996
Recomendado
Clasificación