当前位置: 首页 > news >正文

Java:从单线程计数器到多线程数据同步synchronized和原子类Atomic

目录

    • 使用单线程
    • 使用多线程
    • 使用多线程 + synchronized
    • 使用多线程 + 原子类AtomicLong

使用单线程

单线程修改计数器的值,没有发生问题,每次运行结果都是10000,不过程序耗时较长

package com.example;/*** 计数器*/
class Counter {private static long count;public static long getCount() {return count;}public static void incrementCount() {count++;}
}public class Demo {public static void main(String[] args) throws InterruptedException {long count = Counter.getCount();System.out.println(count);// 0for (int i = 0; i < 10000; i++) {try {Thread.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}Counter.incrementCount();}count = Counter.getCount();System.out.println(count);// 10000}
}

使用多线程

单线程修改计数器的值,运行速度提高了,不过运行结果每次都不一致,而且结果不是10000

package com.example;import java.util.ArrayList;
import java.util.List;/*** 计数器*/
class Counter {private static long count;public static long getCount() {return count;}public static void incrementCount() {count++;}
}public class Demo {public static void main(String[] args) throws InterruptedException {long count = Counter.getCount();System.out.println(count);// 0List<Thread> list = new ArrayList<>();// 启动10000个线程同时访问计数器for (int i = 0; i < 10000; i++) {Thread thread = new Thread(new Runnable() {@Overridepublic void run() {try {Thread.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}Counter.incrementCount();}});list.add(thread);}for (Thread thread : list) {thread.start();}for (Thread thread : list) {thread.join();}count = Counter.getCount();System.out.println(count);}
}

执行结果

第一次:9910
第二次:9912
第三次:9910

使用多线程 + synchronized

多线程加锁后,最后结果都是10000

package com.example;import java.util.ArrayList;
import java.util.List;/*** 计数器*/
class Counter {private static long count;public static long getCount() {return count;}public static synchronized void incrementCount() {count++;}
}public class Demo {public static void main(String[] args) throws InterruptedException {long count = Counter.getCount();System.out.println(count);// 0List<Thread> list = new ArrayList<>();// 启动10000个线程同时访问计数器for (int i = 0; i < 10000; i++) {Thread thread = new Thread(new Runnable() {@Overridepublic void run() {try {Thread.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}Counter.incrementCount();}});list.add(thread);}for (Thread thread : list) {thread.start();}for (Thread thread : list) {thread.join();}count = Counter.getCount();System.out.println(count);}
}

执行结果

第一次:10000
第二次:10000
第三次:10000

使用多线程 + 原子类AtomicLong

多线程中使用原子类AtomicLong实现计数器,最后结果都是10000

原理是CAS(Compare and Set):

  • 先比较原始值和预期值,如果相等,则修改为新值;
  • 不相等则修改失败

伪代码如下

bool compareAndSet(oldValue, expectValue, updateValue){if(oldValue == expectValue){oldValue = updateValue// update success} else{// update fail}
}
package com.example;import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;/*** 计数器*/
class Counter {private static AtomicLong count = new AtomicLong(0);public static long getCount() {return count.get();}public static void incrementCount() {count.incrementAndGet();}
}public class Demo {public static void main(String[] args) throws InterruptedException {long count = Counter.getCount();System.out.println(count);// 0List<Thread> list = new ArrayList<>();// 启动10000个线程同时访问计数器for (int i = 0; i < 10000; i++) {Thread thread = new Thread(new Runnable() {@Overridepublic void run() {try {Thread.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}Counter.incrementCount();}});list.add(thread);}for (Thread thread : list) {thread.start();}for (Thread thread : list) {thread.join();}count = Counter.getCount();System.out.println(count);}
}

执行结果

第一次:10000
第二次:10000
第三次:10000

参考

  1. 使用Atomic-廖雪峰的官方网站
  2. CAS锁机制(无锁、自旋锁、乐观锁、轻量级锁)
  3. java中的Atomic类
http://www.lryc.cn/news/89124.html

相关文章:

  • 提前进入行业顶尖阵营:高性能计算实习的竞争优势
  • Java程序设计入门教程--标识符和关键字
  • 国产IC芯片自动化测试系统ATECLOUD,助力芯片测试自动化
  • BeanFactory和ApplicationContext有什么区别?
  • js的BOM对象中的window、location使用
  • DAY 68 redis高可用的主从复制、哨兵、cluster集群
  • leetcode 1209 学会删除字符串
  • JavaScript6
  • 轻松安装Redis:不用担心配置问题
  • ChatGPT学习研究总结
  • SpringBoot枚举入参实战
  • Ansible介绍
  • GPT-4的免费使用方法分享
  • 一个产品的诞生
  • MQTT与传统的HTTP协议对比,优势在哪里呢?
  • 热榜!阿里出品2023版Java架构师面试指南,涵盖Java所有核心技能
  • 【小程序】封装时间选择组件:用单元格van-cell和插槽slot,包括起始时间和终止时间
  • 华为OD机试真题B卷 Java 实现【猜密码】
  • 沉淀-MYSQL
  • OJ练习第116题——二进制矩阵中的最短路径(BFS)
  • 2023上半年软件设计师真题评析
  • (汇编) 基于VS的x86汇编基础指令
  • 算法Day16 | 104.二叉树的最大深度,559.n叉树的最大深度, 111.二叉树的最小深度,222.完全二叉树的节点个数
  • java设计模式之责任链设计模式的前世今生
  • 是面试官放水,还是公司太缺人了?华为原来这么容易就进了...
  • PLC/DCS系统常见的干扰现象及判断方法
  • c++ 11标准模板(STL) std::map(四)
  • 6.开源非对称加密算法SM2实现
  • Toolformer and Tool Learning(LLMs如何使用工具)
  • 029:Mapbox GL绘制铁路黑白交替的线段