聊聊线程池

首先我们先看看什么是线程?

从JDK1.0开始就有两种创建线程的方法

继承Thread类
实现Runnable接口
复制代码

实际创建线程的操作是init方法

private void init(ThreadGroup g, Runnable target, String name,
                  long stackSize, AccessControlContext acc,
                  boolean inheritThreadLocals)
复制代码

线程有几种状态?

JDK1.5

Callable
Future
FutureTask
复制代码

JDK1.6

RunnableFuture
复制代码

线程池核心类ThreadPoolExecutor

如何创建一个线程池

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory,
                          RejectedExecutionHandler handler)
复制代码

下面对以上参数分别解读:

corePoolSize:核心池的大小设置
maximumPoolSize:池的最大值
keepAliveTime:如果池中当前有多于 corePoolSize 的线程,则这些多出的线程在空闲时间超过 keepAliveTime 时将会终止
unit:keepAliveTime 参数的时间单位
workQueue:传输和保持任务的队列
threadFactory:线程工厂,负责生产新的线程
handler:新任务被拒绝后的执行策略
复制代码

jdk中Executors类给出了一些常用的方法:

1、corePoolSize==maximumPoolSize==nThreads,
    workQueue:new LinkedBlockingQueue<Runnable>(),//无界队列
    keepAliveTime:0
    threadFactory:Executors.defaultThreadFactory()
    handler:new AbortPolicy()
ExecutorService newFixedThreadPool(int nThreads)
ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory)

2、corePoolSize==maximumPoolSize==1,
    workQueue:new LinkedBlockingQueue<Runnable>(),//无界队列
    keepAliveTime:0
    threadFactory:Executors.defaultThreadFactory()
    handler:new AbortPolicy()
ExecutorService newSingleThreadExecutor()
ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory)

3、corePoolSize:0
    maximumPoolSize:Integer.MAX_VALUE,
    workQueue:new SynchronousQueue<Runnable>(),
    keepAliveTime:60
    unit:TimeUnit.SECONDS
    threadFactory:Executors.defaultThreadFactory()
    handler:new AbortPolicy()
ExecutorService newCachedThreadPool()
ExecutorService newCachedThreadPool(ThreadFactory threadFactory)

4、corePoolSize:1
    maximumPoolSize:Integer.MAX_VALUE,
    workQueue:new DelayedWorkQueue(),
    keepAliveTime:0
    threadFactory:Executors.defaultThreadFactory()
    handler:new AbortPolicy()
ScheduledExecutorService newSingleThreadScheduledExecutor()
ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory)

5、corePoolSize:corePoolSize
    maximumPoolSize:Integer.MAX_VALUE,
    workQueue:new DelayedWorkQueue(),
    keepAliveTime:0
    threadFactory:Executors.defaultThreadFactory()
    handler:new AbortPolicy()
ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory)
复制代码

下面是一个使用的例子:

public class ThreadPoolUtil {
    public static final Integer MAXPOOLSIZE = Runtime.getRuntime().availableProcessors();
    public static final ExecutorService USERDEFINED_EXECUTOR = new MyThreadPoolExecutor(MAXPOOLSIZE, MAXPOOLSIZE,
            60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10),
            new MyThreadFactory(),new MyRejected());
}

ThreadPoolUtil.USERDEFINED_EXECUTOR.execute(new MyTask());//起点就是execute,begin...
复制代码

执行流程:

在开始之前先看看这三个变量
    private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
    workerCount:工作线程的数量
    runState:线程状态
        private static final int RUNNING    = -1 << COUNT_BITS;
        private static final int SHUTDOWN   =  0 << COUNT_BITS;
        private static final int STOP       =  1 << COUNT_BITS;
        private static final int TIDYING    =  2 << COUNT_BITS;
        private static final int TERMINATED =  3 << COUNT_BITS;

execute(Runnable command)
        |
addWorker(Runnable firstTask, boolean core)
        |
runWorker(Worker w)
        |
beforeExecute(Thread t, Runnable r)//此处可以自定义,执行任务前
        |
task.run()//实际的任务
        |
afterExecute(Runnable r, Throwable t)//此处可以自定义,执行任务后
        |
processWorkerExit(Worker w, boolean completedAbruptly)
复制代码

相关类的解读 AbstractOwnableSynchronizer

转载于:https://juejin.im/post/5cd0e758e51d456e40377376

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值