你真的掌握了并发编程volatile synchronized么?
发布日期:2021-06-30 18:59:23
浏览次数:2
分类:技术文章
本文共 2313 字,大约阅读时间需要 7 分钟。
先看代码:
import java.util.concurrent.atomic.AtomicInteger;/** * * @author xialuomantian */public class NewTest { static volatile int a = 1; static volatile int b = 1; //static int a = 1; //static int b = 1; public static AtomicInteger aa = new AtomicInteger(0); public static AtomicInteger bb = new AtomicInteger(0); public static AtomicInteger ab = new AtomicInteger(0); static void add() { a++; b++; } static synchronized void print() { if (a > b) { aa.getAndIncrement(); } else if (a < b) { bb.getAndIncrement(); } if (a == b) { ab.getAndIncrement(); } } public static void main(String[] args) { System.out.println(Thread.currentThread().getName()); for (int i = 0; i < 100000; i++) { new Thread(() -> { add(); print(); }).start(); } System.out.println("a>b:" + aa); System.out.println("b>a:" + bb); System.out.println("a==b:" + ab); }}
再去掉volatile
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */package com.mycompany.mytest;import java.util.concurrent.atomic.AtomicInteger;/** * * @author xialuomantian */public class NewTest { static int a = 1; static int b = 1; public static AtomicInteger aa = new AtomicInteger(0); public static AtomicInteger bb = new AtomicInteger(0); public static AtomicInteger ab = new AtomicInteger(0); static void add() { a++; b++; } static synchronized void print() { if (a > b) { aa.getAndIncrement(); } else if (a < b) { bb.getAndIncrement(); } if (a == b) { ab.getAndIncrement(); } } public static void main(String[] args) { System.out.println(Thread.currentThread().getName()); for (int i = 0; i < 100000; i++) { new Thread(() -> { add(); print(); }).start(); } System.out.println("a>b:" + aa); System.out.println("b>a:" + bb); System.out.println("a==b:" + ab); }}
下面是几种结果:
转载地址:https://linuxstyle.blog.csdn.net/article/details/103848279 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
不错!
[***.144.177.141]2024年04月06日 16时34分31秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
基于SSM的兼职论坛系统的设计与实现
2019-04-30
基于java的图书管理系统的设计与实现
2019-04-30
基于java的SSM框架理财管理系统的设计与实现
2019-04-30
基于java的ssm框架就业信息管理系统的设计
2019-04-30
基于java的ssm框架的旅游网站设计与实现
2019-04-30
基于java的SSM框架的流浪猫救助网站的设计与实现
2019-04-30
基于java的SSM框架的教务关系系统的设计与实现
2019-04-30
别再问我什么是A/B测试了!
2019-04-30
如何用同期群分析模型提升留存?(Tableau实战)
2019-04-30
爱了,吹爆这个高颜值的流程图工具!
2019-04-30
一个数据项目
2019-04-30
基于JAVA_JSP电子书下载系统
2019-04-30
基于java出租车计价器设计与实现
2019-04-30
基于java的B2C的网上拍卖系统
2019-04-30
十二时辰篇:这该死的 996
2019-04-30
2021最新 上海互联网公司排名
2019-04-30
字节vs快手!取消大小周之战
2019-04-30
送一个闲置显示器!
2019-04-30
Oracle 行转列 pivot函数基本用法
2019-04-30