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

2019-03-02  本文已影响0人  殊胜因缘_Chris
/**
 * 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)
         */
    }

}
说明:
资料:
  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
上一篇 下一篇

猜你喜欢

热点阅读