美文网首页
1.6 加synchronized关键字解决同步问题

1.6 加synchronized关键字解决同步问题

作者: 殊胜因缘_Chris | 来源:发表于2019-03-02 22:22 被阅读0次
/**
 * This is description.
 * 开启5个线程测试方法同步的结果, synchronized是原子操作, 不可分割.
 * @author Chris Lee
 * @date 2019/3/2 11:09
 */
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(线程名顺序随机, count值依次递减.)
        测试1:
            thread1, count: 9(thread1的count--执行完, 打印输出9)
            thread5, count: 8(thread5的count--执行完, 打印输出8)
            thread2, count: 7(thread2的count--执行完, 打印输出7)
            thread3, count: 6(thread3的count--执行完, 打印输出6)
            thread4, count: 5(thread4的count--执行完, 打印输出5)

        测试2:
            thread1, count: 9(thread1的count--执行完, 打印输出9)
            thread3, count: 8(thread3的count--执行完, 打印输出8)
            thread2, count: 7(thread2的count--执行完, 打印输出7)
            thread5, count: 6(thread5的count--执行完, 打印输出6)
            thread4, count: 5(thread4的count--执行完, 打印输出5)
         */
    }
}
说明:
  • 本篇文章如有不正确或待改进的地方, 欢迎批评和指正, 大家一同进步, 谢谢!
  • 世上有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.6 加synchronized关键字解决同步问题

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