多线程之线程池

1.线程池的优点

减少资源消耗
提高响应速度
提交线程的可管理性

2.线程的生命周期
在这里插入图片描述
3.线程池的执行流程
在这里插入图片描述

4.创建线程池的两种方式

1.通过Executorsc创建,他提供了四种线程池:(不推荐使用)

  • newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
  • newFixedThreadPool(线程池大小)创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
  • newScheduledThreadPool创建一个定长线程池,支持定时及周期性任务执行。以下示例:
  • newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

使用:Executors. …;
注意:newSingleThreadExecutornewFixedThreadPool允许的最大请求队列长度为Integer.MAX_VALUE,可能会堆积大量的请求,导致内存溢出。newCachedThreadPoolnewScheduledThreadPool允许的创建线程的最大数量为Integer.MAX_VALUE,,从而导致内存溢出。

/**
 * newScheduledThreadPool
 * 表示延迟1秒后每3秒执行一次,周期性
 */
public class TestPool003 {
    public static void main(String[] args) {
        ScheduledExecutorService spool = Executors.newScheduledThreadPool(3);
        spool.scheduleAtFixedRate(()-> System.out.println(Thread.currentThread().getName())
            ,1,3, TimeUnit.SECONDS);
    }
}
/**定时
 * scheduledThreadPool
 */
public class TestPool03 {
    public static void main(String[] args) {
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2);
        MyRunnable1 myRunnable0 = new MyRunnable1();
        MyRunnable1 myRunnable2 = new MyRunnable1();
        MyRunnable1 myRunnable3 = new MyRunnable1();
        scheduledThreadPool.schedule(myRunnable0,5, TimeUnit.SECONDS);
        scheduledThreadPool.schedule(myRunnable2,2, TimeUnit.SECONDS);
        scheduledThreadPool.schedule(myRunnable3,30, TimeUnit.SECONDS);
    }
}

class MyRunnable1 implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            final int index = i;
            System.out.println(Thread.currentThread().getName()+"---"+index);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

2.通过ThreadPoolExecutor创建,它有七个参数:

ThreadPoolExecutor(int corePoolSize, //核心线程池大小,始终存在
               int maximumPoolSize, //最大线程数
                long keepAliveTime, //闲线程存活时间,超时则销毁
                     TimeUnit unit, //keepAliveTime的时间计量单位
 BlockingQueue<Runnable> workQueue, //等待阻塞队列
       ThreadFactory threadFactory, //线程工厂
   RejectedExecutionHandler handler) //线程拒绝策略

阻塞队列的类型:
ArrayBlockingQueue

基于数组的有界阻塞队列,按FIFO排序

LinkedBlockingQuene

基于链表的无界阻塞队列(其实最大容量为Interger.MAX),按照FIFO排序。使用该工作队列时,参数maxPoolSize其实是不起作用的。

SynchronousQuene

一个不缓存任务的阻塞队列,也就是说新任务进来时,不会缓存,而是直接被调度执行该任务,如果没有可用线程,则创建新线程,如果线程数量达到maxPoolSize,则执行拒绝策略。

PriorityBlockingQueue

具有优先级的无界阻塞队列,优先级通过参数Comparator实现。

handler拒绝策略:
CallerRunsPolicy

在调用者线程中直接执行被拒绝任务的run方法,除非线程池已经shutdown,则直接抛弃任务。

AbortPolicy

直接丢弃任务,并抛出RejectedExecutionException异常。

DiscardPolicy

该策略下,直接丢弃任务,什么都不做。

DiscardOldestPolicy

该策略下,抛弃进入队列最早的那个任务,然后尝试把这次拒绝的任务放入队列

new ThreadPoolExecutor.AbortPolicy()
new ThreadPoolExecutor.CallerRunsPolicy()
new ThreadPoolExecutor.DiscardPolicy()
new ThreadPoolExecutor.DiscardOldestPolicy()

例如:

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestPoolExecutor {
    public static void main(String[] args) {
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
                5,10,10,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(100),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        poolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName());
            }
        });
        poolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 3; i++) {
                    System.out.println(Thread.currentThread().getName()+"---"+i);
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        //lambda表达式
        poolExecutor.execute(()->System.out.println(Thread.currentThread().getName()));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值