import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* 双重校验保证线程的安全性
* 假如有100个线程,则只会有3个线程进行双重校验,其余97个则直接执行下面代码,比方法锁减少97个阻塞
*如果没有内部的if校验,则会出现,线程进入执行语句
* 如果没有外部的if校验则会有多个线程被阻塞
*/
public class ListThread {
// CopyOnWriteArrayList 对象是一个线程安全的list集合
// 这个集合在修改集合内容时,会将集合内容拷贝到线程自己的内存区域
// 修改后,在将私有区域的数据写入到共享内存区域(假如原有集合内容已经修改过则修改失败)
// static List<Integer> cache=new ArrayList<>();
static List<Integer> cache= new CopyOnWriteArrayList<>();
static List<Integer> selectData(){
if(cache.isEmpty()){//当有3个线程到此拿到时间片
synchronized (cache){//只有一个线程能进入此块代码
if (cache.isEmpty()){//当其余2线程进入是判断时间片是否为空,保证线程安全的同时最大程度保证效率,
cache.add(100);
}//保证业务的原子性,两个
// 方法要么都执行,要么都不执行
}
}
return cache;
}
public static void main(String[] args) {
Thread thread1 = new Thread(() -> System.out.println(selectData()));
Thread thread2 = new Thread(() -> System.out.println(selectData()));
Thread thread3 = new Thread(() -> System.out.println(selectData()));
Thread thread4 = new Thread(() -> System.out.println(selectData()));
Thread thread5 = new Thread(() -> System.out.println(selectData()));
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
}
}
多线程的双重校验
于 2021-10-14 09:38:29 首次发布