你真的掌握了并发编程volatile synchronized么?
2020-02-02 06:52
477 查看
先看代码:
[code] 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
[code]/* * 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); } }
下面是几种结果:
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- 深圳万户6年成功研发出基于微软MOSS平台OA系统,开源OA,可掌握与扩展性整合性强的OA平台
- 轻松掌握一致性哈希算法
- C++高级编程 第八章: 掌握类和对象
- 未来五年程序员需要掌握的10项技能 zz
- [后端人员耍前端系列]Bootstrap篇:30分钟快速掌握Bootstrap
- Web前端工程师要掌握的基础知识和技能
- 掌握C/C++之后,如何在Windows系统下开发有界面的程序?
- 关于NSNotification的使用(重点掌握)
- 转:如何掌握程序语言
- 程序员如何掌握计算机英语(转)
- 从测试到开发掌握 ffmpeg安装 以及amr 转换MP3 并且播放
- 使用Eclipse的几个必须掌握的快捷方式
- SQL SERVER基础知识,掌握超过15项,可以算是基础比较好的了,月薪能过万了。
- 第11章 掌握GCD(唐巧《IOS开发进阶》)
- 三天掌握Kubernetes技术
- 网络工程师应掌握的50个路由器知识要点
- 一篇文章掌握RequireJS常用知识
- 30分钟掌握ES6/ES2015核心内容
- 必须掌握的八个cmd命令
- 掌握需求过程