1、单例模式支持多线程
单例模式:常用的两种模式:饿汉模式 懒汉模式,但这两种模式在多线程应用场景并不安全
为了适用于多线程,保障线程安全,用下面两种:double check instance、static inner class
(1)static inner class
package thread;
/**
* 单例模式,保障线程安全
* static inner class
* 静态内部类形式
*/
public class SingleInner {
private static class Singleton{
private static Singleton single = new Singleton();
}
public static Singleton getInstance(){
return Singleton.single;
}
}
(2)double check instance
public class Singleton{
//私有静态实例,防止被引用
private static Singleton instance = null;
//私有构造方法,防止被实例化
private Singleton(){
}
private static synchronized void syncInit(){
if(instance == null){
instance = new Singleton();
}
}
public static Singleton getInstance(){
if(instance == null){
syncInit();
}
return instance;
}
}
2、同步类容器、并发类容器
同步类:vector hashTable(底层自带synchronid修饰,实现了同步,但是影响并发效率)并发类:Queue、concurrentMap、LinkedBlockingQueue、CopyOnWrite
(1)ConcurrentHashMap:
用段segment划分多个段,每个段相当于hashTable,有对应锁,最高支持16个段每个线程来的时候,访问不同的段
作用:减少锁粒度,减少锁竞争
底层大量使用volatile关键字,实现共享变量
(2)Copy-On-Write(COW)
CopyOnWriteArrayList和CopyOnWriteArraySet写时复制的容器、实现读写分离
当一个线程操作(增删改)容器时,不直接操作该容器,而是复制一个一模一样的容器进行操作,操作完成后,将原容器的指针指向复制的容器。
当有其他线程进行读时,直接读取原容器,实现读写相分离
应用场景:读多写少的时候
3、并发queue
ConcurentLinkedQueue:非阻塞的,性能高,高并发BlockingQueue:阻塞的
ConcurentLinkedQueue:
先进先出,头是最先的,尾