线程状态转换
线程状态.png
方法调用是否释放锁
wait 是
sleep 否
join 释放调用对象的锁(见如下代码)
synchronized(obj){
thread.join(); // join不释放thread的锁
}
synchronized(thread){
thread.join();// join释放锁
}
线程间通信的方式
- volatile、synchronize、lock。(保证可见性)
- wait、notify、notifyAll、singal
- Thread.join()
- ThreadLocal
- 线程中断。
Java内存模型
volatile关键字(保证可见性;禁止指令重排序)
双重检查锁的单例实现
private volatile static Singleton singleton;
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
基于类初始化的解决方案
public class InstanceFactory{
private static class Instance{
public static Instance instance = new Instance();
}
public static Instance getInstance(){
return Instance.instance;
}
}
原子操作类
基本类型(AtomicInteger)、数组类型、引用类型、字段类型
并发工具类
CountDownLatch
CyclidBarrier
Semaphore
Exchanger
如果保证多线程的执行顺序?
阻塞队列与非阻塞队列
非阻塞队列
ConcurrentLinkedQueue
阻塞队列
ArrayBlockingQueue
LinkedBlockingQueue
PriorityBlockingQueue
DelayQueue
SynchronousQueue
LinkedTransferQueue
LinkedBlockingDeque
Fork/Join框架
Executor框架
Executor框架UML图.jpeg
7个核心参数
核心线程数、任务队列、最大线程数、线程工厂、拒绝策略、存活时间、存活时间单位
拒绝策略:直接抛异常、调用线程执行、丢弃一个最近的任务、不处理、自定义处理--实现RejectExecutionHandler接口
如何合理配置线程池???