JAVA concurrent -Executor

structure

Class inheritance graph:

clipboard.png

The above relationship and function of the respective interface / class:

  1. Executor
    actuator interface, but also the top-most abstract core interface, separate from the mission and tasks.
  2. ExecutorService
    provides actuator lifecycle management on the basis of Executor, asynchronous task execution capabilities.
  3. ScheduledExecutorService
    provides the ability to delay the execution / cycle tasks performed in ExecutorService basis.
  4. Executors
    produce specific actuator static factory
  5. ThreadFactory
    thread factory used to create a single thread, a thread is created to reduce the tedious manual work, while being able to reuse the characteristics of the plant.
  6. AbstractExecutorService
    ExecutorService abstract implementation, provide the basis for the realization of all types of actuators class.
  7. ThreadPoolExecutor
    thread pool Executor, is the most commonly used Executor, can manage the thread pool thread.
  8. ScheduledThreadPoolExecutor
    in ThreadPoolExecutor, based on increased support for task scheduling cycle.
  9. ForkJoinPool
    Fork / Join thread pool, when introduced JDK1.7, when implementing core classes Fork / Join framework.

ThreadPoolExecutor

A thread factory

ThreadPoolExecutor when constructing If you do not specify ThreadFactory, is used by default Executors.defaultThreadFactory()create a ThreadFactory, namely Executors.DefaultThreadFactory:

public static ThreadFactory defaultThreadFactory() {
    return new DefaultThreadFactory();
}

/**
 * 默认的线程工厂.
 */
static class DefaultThreadFactory implements ThreadFactory {
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;
 
    DefaultThreadFactory() {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        namePrefix = "pool-" + poolNumber.getAndIncrement() + "-thread-";
    }
 
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
        if (t.isDaemon())
            t.setDaemon(false);
        if (t.getPriority() != Thread.NORM_PRIORITY)
            t.setPriority(Thread.NORM_PRIORITY);
        return t;
    }
}

Worker thread pool task thread

private final class Worker
    extends AbstractQueuedSynchronizer
    implements Runnable
{
    private static final long serialVersionUID = 6138294804551838833L;
    // 这个是真正的线程,任务靠你啦
    final Thread thread;
    // 前面说了,这里的 Runnable 是任务。为什么叫 firstTask?因为在创建线程的时候,如果同时指定了
    // 这个线程起来以后需要执行的第一个任务,那么第一个任务就是存放在这里的(线程可不止执行这一个任务)
    // 当然了,也可以为 null,这样线程起来了,自己到任务队列(BlockingQueue)中取任务(getTask 方法)就行了
    Runnable firstTask;
    // 用于存放此线程完成的任务数,注意了,这里用了 volatile,保证可见性
    volatile long completedTasks;
    // Worker 只有这一个构造方法,传入 firstTask,也可以传 null
    Worker(Runnable firstTask) {
        setState(-1); // inhibit interrupts until runWorker
        this.firstTask = firstTask;
        // 调用 ThreadFactory 来创建一个新的线程
        this.thread = getThreadFactory().newThread(this);
    }
    // 这里调用了外部类的 runWorker 方法
    public void run() {
        runWorker(this);
    }
    ...// 其他几个方法没什么好看的,就是用 AQS 操作,来获取这个线程的执行权,用了独占锁
}

Particular attention initialized here, will this 任务分配给了线程the Thread ,后面调用线程Start ,即调用Worker 中的run` method.

important point

See the source code to note two objects

A task queueBlockingQueue<Runnable> workQueue

It is a collection of task threadHashSet<Worker> workers

The progress of the process thread pool

  • Less than equal to the number of worker threads corePoolSize, where the task firstTaskpackaged worker, and add to workerthe

  • Is greater than the number of worker threads corePoolSizeand can be queued, the task here will be commandthe team toworkQueue
    • There is a special point addWorker(null, false)here is to prevent the task into the team, but the worker thread to 0, this is to add a worker thread, which then add a firstTaskto nullthe workerto workersthe.
  • workQueueQueue is full, less than maximumPoolSize, once again the task firstTaskpackaged workerand added to workersthe.

Above firstTaskpackaged worker, as workerwhen the thread is started, the spin will stop processing tasks, the first process is workerin firstTask, if the firstTaskprocess is terminated or firstTaskis null, then continues to call the getTaskmethod from the queue workQueueget task processing.

reference:

Advanced Java Multithreading (thirty-nine) - JUC's executors framework: executors Framework Overview

Depth interpretation of java thread pool design and source code implementation

Guess you like

Origin www.cnblogs.com/hongdada/p/11983483.html