Java 线程与线程池进阶
时间:2021-08-28
本文章向大家介绍Java 线程与线程池进阶,主要包括Java 线程与线程池进阶使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
1. 线程的状态
Java程序在运行过程中线程可能有6种状态:
- New:新创建状态;
- Runnable:可运行状态;
- Blocked:阻塞状态;
- Waiting:等待状态;
- Timed waiting:超时等待状态;
- Terminated:终止状态;
2. 线程同步
1. 加锁与条件变量
-
- Lock/Unlock:Java代码实现的工具类。
- 重入锁 ReentrantLock:Java 5 引入的,重入锁表示该锁支持一个线程对资源可以重复加锁。
2. Synchronized
分类锁与对象锁
3. Volatile
3. 阻塞队列
1. 什么是阻塞队列
阻塞队列常用于生产者与消费者场景,生产者是往队列里添加元素的线程,消费者是从队列里拿元素的线程。阻塞队列就是生产者存放元素的容器,消费者就是从容器中拿元素的。
2. 阻塞队列的常见使用场景
1. 当队列中没有数据,消费者的线程会自动阻塞(挂起),直到有数据添加到队列中消费者线程才会被唤醒。
2. 当队列中填满数据,生产者的线程会自动阻塞(挂起),直到队列中有空位置,生产者线程才会被唤醒。
以上两种阻塞场景使用的队列就是阻塞队列。
3. Java中的阻塞队列
- ArrayBlockingQueue:由数组结构组成的有界阻塞队列。
- LinkedBlockingQueue:由链表结构组成的有界阻塞队列。
- PriorityBlockingQueue:支持优先级排序的无界阻塞队列。
- DelayQueue:使用优先级队列实现的无界阻塞队列。
- SynchronousQueue:不存储元素的阻塞队列。
- LinkedTransferQueue:由链表结构组成的无界阻塞队列。
- LinkedBlockingDeue:由链表结构组成的双向阻塞队列。
4. 线程池
Java 中线程池工具类:ThreadPoolExecutor:Android 线程池ThreadPoolExecutor类
1. 常用线程池的种类
通过直接或者间接配置ThreadPoolExecutor线程池类的参数可以创建不同类型的线程池。
-
- FixedThreadPool;
- CacheThreadPool;
- SingleThreadExecutor;
- ScheduledThreadPool;
2. FixedThreadPool: 是可重用固定线程数的线程池。
/** * Creates a thread pool that reuses a fixed number of threads * operating off a shared unbounded queue, using the provided * ThreadFactory to create new threads when needed. At any point, * at most {@code nThreads} threads will be active processing * tasks. If additional tasks are submitted when all threads are * active, they will wait in the queue until a thread is * available. If any thread terminates due to a failure during * execution prior to shutdown, a new one will take its place if * needed to execute subsequent tasks. The threads in the pool will * exist until it is explicitly {@link ExecutorService#shutdown * shutdown}. * * @param nThreads the number of threads in the pool * @param threadFactory the factory to use when creating new threads * @return the newly created thread pool * @throws NullPointerException if threadFactory is null * @throws IllegalArgumentException if {@code nThreads <= 0} */ public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory); }
2. CachedThreadPool:根据需要创建线程的线程池,使用的阻塞队列是无存储的阻塞队列。
/** * Creates a thread pool that creates new threads as needed, but * will reuse previously constructed threads when they are * available. These pools will typically improve the performance * of programs that execute many short-lived asynchronous tasks. * Calls to {@code execute} will reuse previously constructed * threads if available. If no existing thread is available, a new * thread will be created and added to the pool. Threads that have * not been used for sixty seconds are terminated and removed from * the cache. Thus, a pool that remains idle for long enough will * not consume any resources. Note that pools with similar * properties but different details (for example, timeout parameters) * may be created using {@link ThreadPoolExecutor} constructors. * * @return the newly created thread pool */ public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
3. SingleThreadExecutor: 单线程的线程池,只有一个核心线程。
/** * Creates an Executor that uses a single worker thread operating * off an unbounded queue. (Note however that if this single * thread terminates due to a failure during execution prior to * shutdown, a new one will take its place if needed to execute * subsequent tasks.) Tasks are guaranteed to execute * sequentially, and no more than one task will be active at any * given time. Unlike the otherwise equivalent * {@code newFixedThreadPool(1)} the returned executor is * guaranteed not to be reconfigurable to use additional threads. * * @return the newly created single-threaded Executor */ public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
4. ScheduledThreadPool:一个能实现定时和周期性任务的线程池。
/** * Creates a thread pool that can schedule commands to run after a * given delay, or to execute periodically. * @param corePoolSize the number of threads to keep in the pool, * even if they are idle * @return a newly created scheduled thread pool * @throws IllegalArgumentException if {@code corePoolSize < 0} */ public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); }
原文地址:https://www.cnblogs.com/naray/p/13055072.html
- Silverlight本地化
- Silverlight 3 创建一个简单的Behavior
- Nodejs学习笔记(六)--- Node.js + Express 构建网站预备知识
- Silverlight 3.0 中的 Local Connection
- 学习Spark——那些让你精疲力尽的坑
- 学习Spark——那些让你精疲力尽的坑
- Silverlight 3.0 中的 WriteableBitmap
- WCF后续之旅(10): 通过WCF Extension实现以对象池的方式创建Service Instance
- Silverlight菜单控件 — CurveMenu
- 实力终端撑腰 两枚域名均五位数被秒
- Silverlight制作逐帧动画 v2 - part2
- Nodejs学习笔记(四)--- 与MySQL交互(felixge/node-mysql)
- 学习Spark——环境搭建(Mac版)
- 离线网络环境下一键式部署
- java教程
- Java快速入门
- Java 开发环境配置
- Java基本语法
- Java 对象和类
- Java 基本数据类型
- Java 变量类型
- Java 修饰符
- Java 运算符
- Java 循环结构
- Java 分支结构
- Java Number类
- Java Character类
- Java String类
- Java StringBuffer和StringBuilder类
- Java 数组
- Java 日期时间
- Java 正则表达式
- Java 方法
- Java 流(Stream)、文件(File)和IO
- Java 异常处理
- Java 继承
- Java 重写(Override)与重载(Overload)
- Java 多态
- Java 抽象类
- Java 封装
- Java 接口
- Java 包(package)
- Java 数据结构
- Java 集合框架
- Java 泛型
- Java 序列化
- Java 网络编程
- Java 发送邮件
- Java 多线程编程
- Java Applet基础
- Java 文档注释
- Borg:Google集群管理大杀器
- 一文了解Zookeeper
- 【投稿】刀哥:Rust学习笔记 4
- Spring Boot 运行源码剖析
- Spring Boot 特性之 Lazy
- Spring Boot 特性之 Banner
- Spring Boot 特性之 Fluent Builder API
- 一文搞懂 Flink Timer
- DATE类型的“小陷阱”
- 简单聊下 Java Agent
- Byte Buddy 基础知识
- 两种在SAP Cloud Application Studio里通过编程对C4C UI字段赋值的方法
- 如何使用 BTrace v.2.0.1
- 三分钟写一个 Java 多线程
- 使用纯粹的ABAP位操作实现两个整数相加