Java线程池总结

线程的生命周期

创建-就绪-运行-阻塞-死亡

调用start和运行run方法

创建多线程的方法:

  1. 继承Thread类,重写run方法,使用start方法创建一个线程
  2. 实现Runnable接口,重写run方法,通过new Thread(Runnable target).start创建一个线程

通过start去创建一个线程,属于线程级别的的调用,而run方法属于方法级的调用,我们常说的现场复用,其实也是做了cas的方法级的调用,让我们误以为是一个多线程。

线程池

  1. executorService1 = Executors.newFixedThreadPool(10);//慢 -----加上睡眠,看起来就像10个一组在运行
  2.  ExecutorService executorService2 = Executors.newCachedThreadPool();//快
  3. ExecutorService executorService3 = Executors.newSingleThreadExecutor();//最慢 --加上睡眠,看起来就像10个一组在运行

线程池的参数:

int corePoolSize,核心线程

int maximumPoolSize,非核心线程

long keepAliveTime,时间

TimeUnit unit,时间单位

BlockingQueue<Runnable> workQueue,队列

 ThreadFactory threadFactory,线程工厂

RejectedExecutionHandler handler 拒绝策略

 

线程提交任务的顺序为:核心线程-队列-非核心线程

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);
    }

线程执行任务的顺序为:核心线程-非核心线程-队列

执行优先级的核心代码
当使用线程复用的核心代码

final void runWorker(Worker w) {
        Thread wt = Thread.currentThread();
        Runnable task = w.firstTask;
        w.firstTask = null;
        w.unlock(); // allow interrupts
        boolean completedAbruptly = true;
        try {
            //或运算时,只要前一个条件满足,后面的就不用执行
            //所以当核心线程为空时,才会去执行getTask()方法,最后执行processWorkerExit方法。
            while (task != null || (task = getTask()) != null) {
                w.lock();
                // If pool is stopping, ensure thread is interrupted;
                // if not, ensure thread is not interrupted.  This
                // requires a recheck in second case to deal with
                // shutdownNow race while clearing interrupt
                if ((runStateAtLeast(ctl.get(), STOP) ||
                     (Thread.interrupted() &&
                      runStateAtLeast(ctl.get(), STOP))) &&
                    !wt.isInterrupted())
                    wt.interrupt();
                try {
                    beforeExecute(wt, task);
                    Throwable thrown = null;
                    //方法级调用,这里也是线程复用的核心
                    try {
                        task.run();
                    } catch (RuntimeException x) {
                        thrown = x; throw x;
                    } catch (Error x) {
                        thrown = x; throw x;
                    } catch (Throwable x) {
                        thrown = x; throw new Error(x);
                    } finally {
                        afterExecute(task, thrown);
                    }
                } finally {
                    task = null;
                    w.completedTasks++;
                    w.unlock();
                }
            }
            completedAbruptly = false;
        } finally {
            processWorkerExit(w, completedAbruptly);
        }
    }


//首先确保当前任务是否完成,完成对时候并释放锁,然后再去工作队列中获取任务。
private void processWorkerExit(Worker w, boolean completedAbruptly) {
        if (completedAbruptly) // If abrupt, then workerCount wasn't adjusted
            decrementWorkerCount();

        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            completedTaskCount += w.completedTasks;
            workers.remove(w);
        } finally {
            mainLock.unlock();
        }

        tryTerminate();

        int c = ctl.get();
        if (runStateLessThan(c, STOP)) {
            if (!completedAbruptly) {
                int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
                if (min == 0 && ! workQueue.isEmpty())
                    min = 1;
                if (workerCountOf(c) >= min)
                    return; // replacement not needed
            }
            addWorker(null, false);
        }
    }

复用的流程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值