java线程池知识总结(附上思维导图)

java线程池知识总结(附上思维导图)

线程池的优点

线程池最大的好处就是减少每次启动、销毁线程的损耗 。

构造方法及参数意义

public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue,
RejectedExecutionHandler handler)

  • corePoolSize:允许核心线程的最大值
  • maximumPoolSize:允许的最大线程数(核心+临时)
  • keepAliveTime+unit:临时线程允许的最长的空闲时间,超过则销毁临时线程
  • workQueue:传递任务的阻塞队列
  • handler:handler:没有能力完成任务时的拒绝策略
    • AbortPolicy:抛出一个 RejectedExecutionException 异常
    • CallerRunsPolicy:由提交任务的线程执行任务
    • DiscardOldestPolicy:丢弃队列中最早的任务
    • DiscardPolicy:丢弃当前任务

执行流程

在这里插入图片描述

简单实现线程池

public class MyThreadPool {
    private int nThreads;                       // 记录允许创建的最大线程数
    private List<Thread> threads;               // 工作线程
    private BlockingQueue<Runnable> workQueue;  // 任务阻塞队列

    private static class Worker extends Thread {
        private BlockingQueue<Runnable> workQueue;

        Worker(BlockingQueue<Runnable> workQueue) {
            this.workQueue = workQueue;
        }

        @Override
        public void run() {
            try {
                while (true) {
                    Runnable target = workQueue.take();
                    target.run();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    MyThreadPool(int nThreads) {
        this.nThreads = nThreads;
        workQueue = new LinkedBlockingQueue<>();    // 所有线程共享同一个阻塞队列对象

        // 提交创建线程
        threads = new ArrayList<>();
        for (int i = 0; i < nThreads; i++) {
            Thread thread = new Worker(workQueue);
            thread.start();
            threads.add(thread);
        }
    }

    void execute(Runnable target) throws InterruptedException {
        workQueue.put(target);
    }

    private static class Target implements Runnable {
        private int n;

        Target(int n) {
            this.n = n;
        }

        @Override
        public void run() {
            System.out.println("执行第"+n+"个线程任务");
        }
    }



    public static void main(String[] args) throws InterruptedException {
        MyThreadPool pool=new MyThreadPool(10);
        for (int i = 1; i <= 10; i++) {
            pool.execute(new Target(i));
        }
    }
}

在这里插入图片描述

shutdown() VS shutdownNow()

  • shutdown():不再接受任何新任务,有序执行完已提交的任务
  • shutdownNow():不再接受新任务,尝试停止所有主动执行的任务,停止等待任务的处理,并返回正在等待执行的任务列表List。 从此方法返回时,这些任务将从任务队列中排除(删除)。

多线程知识思维导图

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值