synchronized实现共同变量访问时的并发安全

丶灬走出姿态 提交于 2020-02-18 15:21:46

1)不安全的代码

package com.atguigu.test;

public class Test {
    public static int count = 0;

    public static void add() {
        count++;
    }

    public static void sub() {
        count--;
    }

    public static void main(String[] args) throws Exception {
        new Thread(() -> {
            for(int i = 0; i < 100000; i++){
                add();
            }
        }).start();

        new Thread(() -> {
            for(int i = 0; i < 100000; i++){
                sub();
            }
        }).start();

        Thread.sleep(2000);

        /**
         * -2879
         *  其实每次访问,发现打印的这个值都不太一样
         */
        System.out.println(count);
    }
}

2)并发安全的代码

package com.atguigu.test;

public class TestSync {
    public static int count = 0;

    public synchronized static void add() {
        count++;
    }

    public synchronized static void sub() {
        count--;
    }

    public static void main(String[] args) throws Exception {
        new Thread(() -> {
            for (int i = 0; i < 100000; i++) {
                add();
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 100000; i++) {
                sub();
            }
        }).start();

        Thread.sleep(2000);

        System.out.println(count); // 始终是0
    }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!