你真的掌握了并发编程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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:高性能微服务架构设计模式@霞落满天
下一篇:K8S的横向自动扩容的功能Horizontal Pod Autoscaling

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2024年04月29日 07时16分13秒