您的位置:首页 > 其它

JUC中 阻塞队列和线程池

2020-03-28 20:16 441 查看

一、阻塞队列(blockQueue)
队列满的时候再放入和空了再取一定会发生阻塞!
父级是queue,和list,set等同级并继承父类collection。另dueue是双端队列,效率高,其中同步队列SynchronousQueue一次只有一个元素。不会造成阻塞 队列的存入和取值策略:

方法 第一组会抛出异常 返回一个布尔值,不会抛出异常 延时等待 一直等待
插入 add() offer(e) offer(e,time) put()
取出 remove() poll() poll(time) take()
检查 element() peek() - -

二、线程池
提高程序性能,充分利用计算机的资源。
了解线程池的3+7+4
1、3大方法(阿里不允许使用,会出OOM异常,最大是integer.MAX_VALUE,2的31次方,CPU冒烟)

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolDemo01 {
public static void main(String[] args) {
// 单例,只能有一个线程!
//        ExecutorService threadPool = Executors.newSingleThreadExecutor();
// 固定的线程数
//         ExecutorService threadPool = Executors.newFixedThreadPool(8);
// 遇强则强!可伸缩!
//         ExecutorService threadPool = Executors.newCachedThreadPool();

try {
// 线程池的使用方式!
for (int i = 0; i < 30; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName() + " ok");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 使用完毕后需要关闭!
threadPool.shutdown();
}

}
}

2、7大参数

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

3、4大拒绝策略

* 1、ThreadPoolExecutor.AbortPolicy();  抛出异常,丢弃任务
* 2、ThreadPoolExecutor.DiscardPolicy();不抛出异常,丢弃任务
* 3、ThreadPoolExecutor.DiscardOldestPolicy(); 丢弃前尝试获取任务,不一定执行!
* 4、ThreadPoolExecutor.CallerRunsPolicy(); 哪来的去哪里找对应的线程执行!

4、最大线程池的设置

CPU密集型: 根据CPU的处理器数量来定!保证最大效率,获得服务器cpu核数:Runtime.getRuntime().availableProcessors();

IO密集型: 50 个线程都是进程操作大io资源, 比较耗时! > 这个常用的 IO 任务数!
  • 点赞
  • 收藏
  • 分享
  • 文章举报
qq_28945483 发布了6 篇原创文章 · 获赞 0 · 访问量 67 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: