Thread pools (emphasis)

Thread pool: Three methods, seven parameters, and four rejection policies

Pooling technology

The operation of the program, the essence: occupy the resources of the system! Optimize the use of resources! => Pooling technology

Thread pool, JDBC connection pool, memory pool, object pool ///…… Create, destroy. Very waste of resources

Pooling technology: prepare some resources in advance, and if someone wants to use them, come to me to take them and return them to me after using them.

Default size: 2

max:

Benefits of thread pools:

1. Reduce resource consumption

2, improve the speed of response

3, convenient management.

Thread reuse, can control the maximum number of concurrent, management threads

Thread pools: Three methods

package com.chao.pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//Executors Tools, 3 major methods
public class Demo01 {
    public static void main(String[] args) {
// ExecutorService threadPool = Executors.newSingleThreadExecutor(); // Single thread
        ExecutorService threadPool = Executors.newFixedThreadPool(5); // Create a fixed thread pool size
// ExecutorService threadPool = Executors.newCachedThreadPool(); // Retractable, strong when strong, weak when weak
        try {
            for (int i = 0; i < 100; i++) {
                //new Thread().start();
                // After using thread pools, use thread pools to create threads
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName()+" ok"); }); }}catch (Exception e) {
            e.printStackTrace();
        } finally {
            // The thread pool is used up, the program ends, close the thread poolthreadPool.shutdown(); }}}Copy the code

Seven parameters

Source code analysis

public static ExecutorService newSingleThreadExecutor(a) {
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1.1.0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>()));
}
Copy the code
public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
}
Copy the code
public static ExecutorService newCachedThreadPool(a) {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE, // 2.1 billion OOM overflow
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
}
Copy the code
// Essence: ThreadPoolExecutor
public ThreadPoolExecutor(intCorePoolSize, // Core thread pool sizeintMaximumPoolSize,// Maximum core thread pool sizelongkeepAliveTime, BlockingQueue<Runnable> workQueue, BlockingQueue<Runnable> workQueue, ThreadFactory ThreadFactory, ThreadFactory, ThreadFactory, RejectedExecutionHandler Handler) {// Reject the policy
    if (corePoolSize < 0 ||
        maximumPoolSize <= 0 ||
        maximumPoolSize < corePoolSize ||
        keepAliveTime < 0)
        throw new IllegalArgumentException();
    if (workQueue == null || threadFactory == null || handler == null)
        throw new NullPointerException();
    this.corePoolSize = corePoolSize;
    this.maximumPoolSize = maximumPoolSize;
    this.workQueue = workQueue;
    this.keepAliveTime = unit.toNanos(keepAliveTime);
    this.threadFactory = threadFactory;
    this.handler = handler;
}
Copy the code

Create a thread pool manually

package com.chao.pool;
import java.util.concurrent.*;
//Executors Tools, 3 major methods
public class Demo {
    public static void main(String[] args) {
        // Custom thread pool! Work ThreadPoolExecutor
        ExecutorService threadPool = new ThreadPoolExecutor(
                2.5.3,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy()); // When the queue is full, try to compete with the earliest one without throwing an exception!
        try {
            // Max load: Deque + Max
            / / more than: RejectedExecutionException
            for (int i = 1; i <= 9; i++) {
                //new Thread().start();
                // After using thread pools, use thread pools to create threads
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName()+" ok"); }); }}catch (Exception e) {
            e.printStackTrace();
        } finally {
            // The thread pool is used up, the program ends, close the thread poolthreadPool.shutdown(); }}}Copy the code

Four rejection strategies

/ * * * new ThreadPoolExecutor. AbortPolicy () / / bank full, and people come in, don't deal with this person, An exception is thrown. * new ThreadPoolExecutor CallerRunsPolicy () / / which come of where to go! * new ThreadPoolExecutor DiscardPolicy () / / queue is full, the task he lost never throw an exception. * new ThreadPoolExecutor DiscardOldestPolicy () / / queue is full, the attempt to and the first competition, also won't throw an exception! * /
Copy the code

Summary and expansion

How to set the maximum size of the pool thread!

Understand: IO intensive, CPU intensive: (tuning)

package com.chao.pool;
import java.util.concurrent.*;
public class Demo {
    public static void main(String[] args) {
        // Custom thread pool! ThreadPoolExecutorpython train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/faster_rcnn_inception_v2_pets.config

        // How to define the maximum thread
        //1, CPU intensive, a few cores, just a few, can maintain the highest efficiency of CPU! 16 threads running at the same time!
        //2, I/o intensive > determine your application is very IO intensive threads,
        // Program 15 large tasks IO very heavy resources!
        // Get the number of CPU cores
        System.out.println(Runtime.getRuntime().availableProcessors());
        ExecutorService threadPool = new ThreadPoolExecutor(
                2,
                Runtime.getRuntime().availableProcessors(),
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy()); // When the queue is full, try to compete with the earliest one without throwing an exception!
        try {
            // Max load: Deque + Max
            / / more than: RejectedExecutionException
            for (int i = 1; i <= 9; i++) {
                //new Thread().start();
                // After using thread pools, use thread pools to create threads
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName()+" ok"); }); }}catch (Exception e) {
            e.printStackTrace();
        } finally {
            // The thread pool is used up, the program ends, close the thread poolthreadPool.shutdown(); }}}Copy the code