美文网首页
1.11 Synchronized在遇到异常时, 默认情况下,

1.11 Synchronized在遇到异常时, 默认情况下,

作者: 殊胜因缘_Chris | 来源:发表于2019-03-10 20:22 被阅读0次
    /**
     * This is description.
     * Synchronized在遇到异常时, 默认情况下, 会释放锁.
     *
     * @author Chris Lee
     * @date 2019/3/4 22:52
     */
    public class Demo implements Runnable {
    
        private int count = 0;
        boolean flag = true;
    
        @Override
        public synchronized void run() {
            while (flag) {
                count++;
                System.out.println(Thread.currentThread().getName() + ", count: " + count);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (count == 5) {
                    int i = 1 / 0;
                    System.out.println(i);
                }
            }
        }
    
        public static void main(String[] args) {
            Demo demo = new Demo();
    
            new Thread(() -> demo.run(), "t1").start();
            new Thread(() -> demo.run(), "t2").start();
            /*
                t1, count: 1
                t1, count: 2
                t1, count: 3
                t1, count: 4
                t1, count: 5
                t2, count: 6
                Exception in thread "t1" java.lang.ArithmeticException: / by zero
                    at com.chris.concurrency1.c011synmeetexception.Demo.run(Demo.java:28)
                    at com.chris.concurrency1.c011synmeetexception.Demo.lambda$main$0(Demo.java:37)
                    at java.lang.Thread.run(Thread.java:745)
                t2, count: 7
                t2, count: 8
                t2, count: 9
                t2, count: 10
             */
        }
    }
    
    
    说明:
    • 本篇文章如有不正确或待改进的地方, 欢迎批评和指正, 大家一同进步, 谢谢!
    • 世上有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.11 Synchronized在遇到异常时, 默认情况下,

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