美文网首页
1.5 不加synchronized关键字产生的同步问题

1.5 不加synchronized关键字产生的同步问题

作者: 殊胜因缘_Chris | 来源:发表于2019-03-02 22:17 被阅读0次
    /**
     * This is description.
     * 开启5个线程测试方法不同步的结果, 此时会出现同步问题.
     *
     * @author Chris Lee
     * @date 2019/3/1 21:31
     */
    public class Demo implements Runnable {
        private int count = 10;
    
        @Override
        public /*synchronized*/ void run() {
            count--;
            System.out.println(Thread.currentThread().getName() + ", count: " + count);
        }
    
        public static void main(String[] args) {
            Demo demo = new Demo();
            for (int i = 0; i < 5; i++) {
                // start(): 线程开启, 调用run(). 此时5个线程同时去获取锁, 哪个线程先获取锁是不确定的.
                new Thread(demo, "thread" + (i + 1)).start();
            }
            /*
            不加synchronized(打印结果随机, 下面分析两组, 可以自行分析.)
            测试1:
                thread1, count: 9(thread1的count--执行完, 打印输出9)
                thread3, count: 7(thread1的count--执行完(9), thread3的count--和thread4的count--都执行完(7), 打印输出7)
                thread4, count: 7(thread1的count--执行完(9), thread3的count--和thread4的count--都执行完(7), 打印输出7)
                thread2, count: 6(thread1的count--执行完(9), thread3的count--和thread4的count--都执行完(7), thread2的count--执行完(6), 打印输出6)
                thread5, count: 5(thread1的count--执行完(9), thread3, thread4, thread2, thread5的count--执行完(5), 打印输出5)
    
            测试2:
                thread1, count: 9(thread1的count--执行完, 打印输出9)
                thread3, count: 8(thread1的count--执行完, thread3的count--执行完, 打印输出8)
                thread5, count: 7(thread1的count--执行完(9), thread2的count--和thread3的count--都执行完(8), thread5的count--执行完(7), 打印输出7)
                thread2, count: 8(thread1的count--执行完, thread2的count--执行完, 打印输出8)
                thread4, count: 6(thread1的count--执行完(9), thread2的count--和thread3的count--都执行完(8), thread5的count--执行完(7), thread4的count--执行完(6), 打印输出6)
             */
        }
    
    }
    
    说明:
    • 本篇文章如有不正确或待改进的地方, 欢迎批评和指正, 大家一同进步, 谢谢!
    • 世上有4样东西可以让世界变得更美好, 它们是: 代码(Code), 诗(Poem), 音乐(Music), 爱(Love). 如有兴趣了解更多, 欢迎光顾"我的文集"相关文章.
    资料:
    1. 学习视频: https://www.bilibili.com/video/av11076511/?p=1
    2. 参考代码: https://github.com/EduMoral/edu/tree/master/concurrent/src/yxxy
    3. 我的代码: https://github.com/ChrisLeejing/learn_concurrency.git

    相关文章

      网友评论

          本文标题:1.5 不加synchronized关键字产生的同步问题

          本文链接:https://www.haomeiwen.com/subject/mwxuuqtx.html