你真的掌握了并发编程volatile synchronized么?
发布日期:2021-06-30 18:59:23
浏览次数:3
分类:技术文章
本文共 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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
初次前来,多多关照!
[***.217.46.12]2024年04月29日 07时16分13秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Python 之 Scatter散点图
2019-04-30
Python实现决策树 Desision Tree & 可视化
2019-04-30
决策树 Decision tree
2019-04-30
nominal和ordinal & 数据处理中四种基本数据类型
2019-04-30
Python 实现 Cross-validation
2019-04-30
Grid SearchCV(网格搜索)& Python实现
2019-04-30
ROS相关知识
2019-04-30
单目深度估计 monodepth2模型 代码
2019-04-30
位图索引Bitmap indexes
2019-04-30
YOLO算法(二)—— Yolov2 & yolo9000
2019-04-30
YOLO算法(三)—— Yolov3 & Yolo系列网络优缺点
2019-04-30
Python的__future__模块
2019-04-30
计算机视觉中的cost-volume的概念具体指什么(代价体积)
2019-04-30
启发函数heuristic 与 A*
2019-04-30