Multithreading (six) thread pool

1. Environment

   idea

2. What is multi-threading and what are the benefits of using multi-threading

Those who have a database foundation should understand the database connection pool: the role is to manage database connections

The role of the thread pool is the same as that of the database connection pool: it is used to manage threads

2.1 Benefits

First: reduce resource consumption . Reduce the cost of thread creation and destruction by reusing already created threads . Second: improve the response speed . When a task arrives , the task can be executed immediately without waiting for the thread to be created . Third: improve the manageability of threads . 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.The thread pool can be uniformly allocated, tuned and monitored .

 

Three. Several ways to create multithreading

After jdk1.5, jdk provides us with Executors in the concurrent package to create thread pools

 

3.1newCachedThreadPool (cacheable thread pool)

Create a cacheable thread pool. If the length of the thread pool exceeds the processing needs, idle threads can be flexibly recycled. If there is no recycling, new threads will be created.

 public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();

        for ( int i=0;i<10;i++){ // Create 10 threads 
            final  int temp= i;
            executorService.execute( new Runnable() {
                 public  void run() { // The business code of thread scheduling 
                    System.out.println(Thread.currentThread().getName()+",i:"+ temp);
                }
            });
        }
        executorService.shutdown(); // Close the thread pool 
    }

 It can be seen from the running results that although 10 threads are created using the code, only 9 are actually created, indicating that some threads are reused. After looking at the source code. . . .

Open the ThreadPoolExecutor() method to discover,

int corePoolSize,//The number of core threads to create a thread pool 
int maximumPoolSize,//The maximum number of threads to create a thread pool
long keepAliveTime,//Wait time
TimeUnit unit,//Unit
BlockingQueue<Runnable> workQueue//The bottom layer


can use blocking queue storage Knowing that the cacheable thread pool does not create a core thread pool, the maximum number of threads is equal to the maximum value of int

 

 

3.2 newFixedThreadPool (fixed-length thread pool)

Create a fixed-length thread pool to control the maximum number of concurrent threads. Exceeded threads will wait in the queue.

public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        for ( int i=0;i<10;i++){ // Create 10 threads 
            final  int temp= i;
            executorService.execute( new Runnable() {
                 public  void run() { // The business code of thread scheduling 
                    System.out.println(Thread.currentThread().getName()+",i:"+ temp);
                }
            });
        }
        executorService.shutdown(); // Close the thread pool 
    }

 The result shows that there are only three threads, so does it prove that the fixed-length thread pool creates the number of threads of the specified length! ! ! ! ! View source code

It was found that the source code called the ThreadPoolExecutor() method and passed the input parameters



So it can be concluded that the number of thread pools of fixed-length thread pools is fixed .

3.3 newFixedThreadPool (timed thread pool)

Create a fixed-length thread pool to support scheduled and periodic task execution

public static void main(String[] args) {


        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);

        for ( int i=0;i<10;i++){ // Create 10 threads 
            final  int temp= i;

            scheduledExecutorService.schedule( new Runnable() {
                 public  void run() { // The business code of thread scheduling 
                    System.out.println(Thread.currentThread().getName()+",i:"+ temp);
                }
            },3, TimeUnit.SECONDS);
        }
        scheduledExecutorService.shutdown(); // Close the thread pool 
    }

 

 

The effect is called when the program runs for 3 seconds. Because the running effect is similar to the fixed length. So look at the source code to see if only 3 threads are created.

So it can be seen that the length of the thread that can be timed is not the specified length, but the maximum value of Int

 

 

3.3 newSingleThreadExecutor (single-threaded thread pool)

Create a single-threaded thread pool that only uses a single worker thread to execute tasks, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority)

public static void main(String[] args) {


        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

        for ( int i=0;i<10;i++){ // Create 10 threads 
            final  int temp= i;

            scheduledExecutorService.execute( new Runnable() {
                 public  void run() { // The business code of thread scheduling 
                    System.out.println(Thread.currentThread().getName()+",i:"+ temp);
                }
            });
        }
        scheduledExecutorService.shutdown(); // Close the thread pool 
    }

 

 Same as above, look at the source code

From the source code, it can be seen that the single-threaded thread pool only creates one thread

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325918658&siteId=291194637