线程池相关 源码查看

private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));

public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        /*
         * Proceed in 3 steps:
         *
         * 1. If fewer than corePoolSize threads are running, try to
         * start a new thread with the given command as its first
         * task.  The call to addWorker atomically checks runState and
         * workerCount, and so prevents false alarms that would add
         * threads when it shouldn't, by returning false.
         *
         * 2. If a task can be successfully queued, then we still need
         * to double-check whether we should have added a thread
         * (because existing ones died since last checking) or that
         * the pool shut down since entry into this method. So we
         * recheck state and if necessary roll back the enqueuing if
         * stopped, or start a new thread if there are none.
         *
         * 3. If we cannot queue task, then we try to add a new
         * thread.  If it fails, we know we are shut down or saturated
         * and so reject the task.
         */
        int c = ctl.get();
// 当前线程数<核心线程数,
        if (workerCountOf(c) < corePoolSize) {
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        if (isRunning(c) && workQueue.offer(command)) {
            int recheck = ctl.get();
            if (! isRunning(recheck) && remove(command))
                reject(command);
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        else if (!addWorker(command, false))
            reject(command);
    }

线程运行状态:

running:-1 可以接收新任务,也可以处理队列里的任务

shutdown:0 不接收新的任务,可以处理队列里的任务

stop:1 不接收新的任务,不处理队列里的任务

tiding:2  不接收新的任务,不处理队列里的任务

terminated:3 不接收新的任务,不处理队列里的任务

   ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                10, // 核心线程数
                30, // 最大线程数                0,
                TimeUnit.HOURS,
                new LinkedBlockingDeque<>(5) // 队列 
        );


提交优先级:
// 100个任务:
1)1-10 核心线程数 
2)11-15 队列里,此时队列容量为5
3)16-36 新建线程,30-10 = 20个
4)拒绝策略 -- 37的时候运行报错:AbortPolicy 默认

执行优先级:
1)核心线程数
2)最大线程数
3)队列
因此,执行顺序为 1-10 16-36 11-15

ThreadPoolExcutor内部有4种拒绝策略:
1)CallerRunsPolicy:由调用execute方法提交任务的线程来执行这个任务
2) AbortPolicy:抛出异常RejectedExcutionException拒绝提交任务,default 默认用这个
3) DiscardPolicy:直接抛弃任务,不做任何处理
4) DiscardOldestPolicy:去除任务队列中的第一个任务(最旧的),重新提交

一般会自定义 RejectdExcutionHandler接口,存数据库。








  /*
     * Methods for creating, running and cleaning up after workers
     */

    /**
     * Checks if a new worker can be added with respect to current
     * pool state and the given bound (either core or maximum). If so,
     * the worker count is adjusted accordingly, and, if possible, a
     * new worker is created and started, running firstTask as its
     * first task. This method returns false if the pool is stopped or
     * eligible to shut down. It also returns false if the thread
     * factory fails to create a thread when asked.  If the thread
     * creation fails, either due to the thread factory returning
     * null, or due to an exception (typically OutOfMemoryError in
     * Thread.start()), we roll back cleanly.
     *
     * @param firstTask the task the new thread should run first (or
     * null if none). Workers are created with an initial first task
     * (in method execute()) to bypass queuing when there are fewer
     * than corePoolSize threads (in which case we always start one),
     * or when the queue is full (in which case we must bypass queue).
     * Initially idle threads are usually created via
     * prestartCoreThread or to replace other dying workers.
     *
     * @param core if true use corePoolSize as bound, else
     * maximumPoolSize. (A boolean indicator is used here rather than a
     * value to ensure reads of fresh values after checking other pool
     * state).
     * @return true if successful
     */
    private boolean addWorker(Runnable firstTask, boolean core) {
        retry:

        for (;;) {
            int c = ctl.get();
//获取当前线程状态
            int rs = runStateOf(c);

            // Check if queue empty only if necessary.
// 如果大于shutdown状态:返回false 不再增加线程
            if (rs >= SHUTDOWN &&
                ! (rs == SHUTDOWN &&
                   firstTask == null &&
                   ! workQueue.isEmpty()))
                return false;

            for (;;) {
// 获取当前线程数,看是否超过最大线程数,如果超出,返回false,不再增加
                int wc = workerCountOf(c);
                if (wc >= CAPACITY ||
                    wc >= (core ? corePoolSize : maximumPoolSize))
                    return false;
// 如果当前线程数<最大线程数,自增+1,退出循环,后续有增加线程逻辑
                if (compareAndIncrementWorkerCount(c))
                    break retry;
                c = ctl.get();  // Re-read ctl
                if (runStateOf(c) != rs)
                    continue retry;
                // else CAS failed due to workerCount change; retry inner loop
            }
        }

        boolean workerStarted = false;
        boolean workerAdded = false;
        Worker w = null;
        try {
// Worker extends AbstractQueuedSynchronizer implement Runnable, 复写run(),  调用start()运行
            w = new Worker(firstTask);
            final Thread t = w.thread;
            if (t != null) {
// 并发运行上锁
                final ReentrantLock mainLock = this.mainLock;
                mainLock.lock();
                try {
                    // Recheck while holding lock.
                    // Back out on ThreadFactory failure or if
                    // shut down before lock acquired.
                    int rs = runStateOf(ctl.get());

                    if (rs < SHUTDOWN ||
                        (rs == SHUTDOWN && firstTask == null)) {
                        if (t.isAlive()) // precheck that t is startable
                            throw new IllegalThreadStateException();
                        workers.add(w);
                        int s = workers.size();
                        if (s > largestPoolSize)
                            largestPoolSize = s;
                        workerAdded = true;
                    }
                } finally {
                    mainLock.unlock();
                }
                if (workerAdded) {
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
                addWorkerFailed(w);
        }
        return workerStarted;
    }

进程:操作系统会以进程为单位,分配系统资源(CPU时间片,内存等资源),是资源分配的最小单位。

线程:CPU调度的最小单位

进程间的通信方式: pipe/named pipe,signal,message queue,shared memory,semaphore(可以用来做限流),socket

线程间通信:共享内存

分布式锁: mysql zk redies

线程同步:一个线程依赖另一个线程的消息,当没有个到另一个消息时,应等待,直到消息到达时才被唤醒。

线程互斥:当多个线程需要访问同一共享资源时,任何时刻最多只允许一个线程去使用,其他线程等待,知道资源被释放。

上下文切换只能在内核模式下发生。

内核态:kernel mode Ring 0 1 2

Ring 3(用户态) 

用户态:user mode

应用程序崩溃不会向影像内核的运行

应用程序一般会在以下几种情况切换到内核模式:

1)系统调用。thread, lock

2)异常事件

3)设备中断

线程的生命周期:

操作系统层面:初始状态,start()可运行状态,运行状态,休眠状态,终止状态

java: new, running, termiated, timed_waiting, waiting(.wait(),.join(),LockSupport.park()), blocked(synchronized)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
线程池ThreadPoolExecutor)是 Java 中用于管理和执行线程的机制。下面是ThreadPoolExecutor源码的剖析: ```java public class ThreadPoolExecutor extends AbstractExecutorService { // 省略其他成员变量 public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { // 根据参数创建线程池 } // 省略其他构造方法和方法重载 public void execute(Runnable command) { // 执行任务,将任务提交给线程池进行处理 } // 省略其他方法 private void runWorker(Worker w) { // 工作线程执行具体任务的逻辑 Runnable task = w.firstTask; w.firstTask = null; boolean completedAbruptly = true; try { while (task != null || (task = getTask()) != null) { // 执行任务 task.run(); task = null; } completedAbruptly = false; } finally { processWorkerExit(w, completedAbruptly); } } // 省略其他内部类和方法 } ``` 上述代码展示了ThreadPoolExecutor的主要结构。它是一个实现了ExecutorService接口的具体类,在Java中用于执行和管理线程池。 在构造方法中,我们可以设置核心线程数(corePoolSize)、最大线程数(maximumPoolSize)、空闲线程的存活时间(keepAliveTime)、时间单位(unit)和阻塞队列(workQueue)等参数。 execute方法用于向线程池提交任务,任务将被封装成一个Runnable对象,然后由线程池中的工作线程执行。 runWorker方法被工作线程调用,用于执行具体的任务逻辑。它不断地从阻塞队列中获取任务并执行,直到阻塞队列为空或工作线程被中断。 这只是ThreadPoolExecutor源码的简要剖析,了解更多细节可以查看源码实现。希望对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值