一、阻塞队列
-
ArrayBlockingQueue : 一个由数组结构组成的有界阻塞队列。
LinkedBlockingQueue : 一个由链表结构组成的有界阻塞队列。
PriorityBlockingQueue : 一个支持优先级排序的无界阻塞队列。
DelayQueue: 一个使用优先级队列实现的无界阻塞队列。
SynchronousQueue: 一个不存储元素的阻塞队列。
LinkedTransferQueue: 一个由链表结构组成的无界阻塞队列。
LinkedBlockingDeque: 一个由链表结构组成的双向阻塞队列。
BlockingQueue接口: 单向阻塞队列实现了该接口。
BlockingDeque接口: 双向阻塞队列实现了该接口。 -
使用场景:多线程并发处理,线程池!
-
API:
方法描述 抛出异常 返回特殊的值 一直阻塞 超时退出 插入数据 add(e) offer(e) put(e) offer(e,time,unit) 获取并移除队列的头 remove() poll() take() poll(time,unit) 获取但不移除队列的头 element() peek() 不可用 不可用 -
SynchronousQueue 同步队列:进去一个元素,必须等待取出来之后,才能再往里面放一个元素!
二、线程池(重点)
-
不允许用Executors工具创建线程池,直接用 ThreadPoolExecutor:
-
public ThreadPoolExecutor(int corePoolSize, // 核心线程池大小 int maximumPoolSize, // 最大线程池大小 long keepAliveTime, // 非核心线程池超时释放时间 TimeUnit unit, // 超时单位 BlockingQueue<Runnable> workQueue,// 阻塞队列 ThreadFactory threadFactory,// 线程工厂 RejectedExecutionHandler handler// 拒绝策略 ) { if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0) throw new IllegalArgumentException(); if (workQueue == null || threadFactory == null || handler == null) throw new NullPointerException(); this.acc = System.getSecurityManager() == null ? null : AccessController.getContext(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; }
-
Executors创建线程池三大方法:newSingleThreadExecutor(),newFixedThreadPool(5),newCachedThreadPool()
-
ThreadPoolExecutor 创建线程池,七大参数
-
4种拒绝策略
new ThreadPoolExecutor.AbortPolicy() //不处理,抛出异常 new ThreadPoolExecutor.CallerRunsPolicy() //哪来的回哪去(main线程) new ThreadPoolExecutor.DiscardOldestPolicy() //丢掉任务,不抛出异常 new ThreadPoolExecutor.DiscardPolicy() //尝试去和最早的竞争,不抛出异常!
三、新时代程序员必会:
-
- lambda表达式
- 链式编程
- 函数式Function接口:只有一个方法的接口,(Consumer接口,Predicate接口,Supplier接口)
- Stream流式计算
public class StreamTest { /*** 题目要求:一分钟内完成此题,只能用一行代码实现! * 现在有5个用户!筛选: * * 1、ID 必须是偶数 * * 2、年龄必须大于23岁 * * 3、用户名转为大写字母 * * 4、用户名字母倒着排序 * * 5、只输出一个用户! * */ public static void main(String[] args) { User james = new User(101, "James", 37); User james1 = new User(102, "James2", 34); User james2 = new User(103, "James3", 32); User james3 = new User(104, "James4", 38); //存储:可以是集合、MySQL等 List<User> list = Arrays.asList(james, james1, james2, james3); //计算:Stream流 // lambda表达式、链式编程、函数式接口、Stream流式计算 list.stream() .filter((user -> {return user.getId() % 2 == 0;})) .filter(user -> {return user.getAge() > 23;}) .map(user -> {return user.getName().toUpperCase();}) .sorted((a, b) -> {return b.compareTo(a);}) .limit(1) .forEach(System.out :: println); } }
-
ForkJion(分支合并计算:计算量大提高效率)
- 相当于Map-Reduce
- 工作窃取(线程B执行完自己任务后,窃取线程A的任务执行,提高效率)
-
异步回调(Future - CompletableFuture)-----> 类似于Ajax异步调用