thread09 - 抛出异常释放锁

package com.neutron.t09;

import java.util.concurrent.TimeUnit;

/**
 * 问题:程序在执行过程中,如果发生异常,那么会不会释放锁?
 */
public class T09 {
    int count = 0;

    public synchronized void set2() {
        System.out.println(Thread.currentThread().getName() + " start");
        while (true) {
            count ++;
            System.out.println(Thread.currentThread().getName() + " count:" + count);

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (count % 3 == 1) {
                // 此处抛出异常,锁会被释放,要想不释放锁,可以在这里进行catch,然后让循环继续执行下去。
                int exception = 1/0;
            }
        }

    }

    public synchronized void get3() {
        set2();
    }

    /**
     运行结果:
         Thread-0 start
         Thread-0 count:1
         Exception in thread "Thread-0" java.lang.ArithmeticException: / by zero
         at com.neutron.t09.T09.set2(T09.java:25)
         at java.lang.Thread.run(Thread.java:745)
         看看发生异常是否会释放锁呢?
         Thread-1 start
         Thread-1 count:2
         Thread-1 count:3
         Thread-1 count:4
         Exception in thread "Thread-1" java.lang.ArithmeticException: / by zero
         at com.neutron.t09.T09.set2(T09.java:25)
         at com.neutron.t09.T09.get3(T09.java:33)
         at java.lang.Thread.run(Thread.java:745)

     */
    public static void main(String[] args) {
        T09 t09 = new T09();
        new Thread(t09::set2).start();

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("看看发生异常是否会释放锁呢?");
        new Thread(t09::get3).start();
    }
}

/*
    解说:
    1.如果发生异常不释放,直接抛出异常不释放锁,那么第二个线程将不会执行。
      即new Thread(t09::get3).start();不会执行。
      如果new Thread(t09::get3).start();执行,那么就表示发生异常直接抛出异常,会释放锁。
 */

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值