多线程的双重校验

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();
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值