2.1.7出现异常的线程自动释放锁

package cha02.execise09;

/**
 * Created by sunyifeng on 17/9/24.
 */
public class Service {
    synchronized public void testMethod() {
        if (Thread.currentThread().getName().equals("a")) {
            System.out.println("thread name:" + Thread.currentThread().getName() + ",当前时间:" + System.currentTimeMillis());
            while (true) {
                if (("" + Math.random()).substring(0, 8).equals("0.123456")) {
                    System.out.println("thread name:" + Thread.currentThread().getName() + ",当前时间:" + System.currentTimeMillis());
                    // TODO: 这里出现异常
                    Integer.parseInt("a");
                }
            }
        } else {
            System.out.println("Thread B run time = " + System.currentTimeMillis());
        }
    }
}
package cha02.execise09;

/**
 * Created by sunyifeng on 17/9/24.
 */
public class ThreadA extends Thread {
    private Service service;

    public ThreadA(Service service) {
        super();
        this.service = service;
    }

    @Override
    public void run(){
        service.testMethod();
    }
}
package cha02.execise09;

/**
 * Created by sunyifeng on 17/9/24.
 */
public class ThreadB extends Thread {
    private Service service;

    public ThreadB(Service service) {
        super();
        this.service = service;
    }

    @Override
    public void run(){
        service.testMethod();
    }
}
package cha02.execise09;


/**
 * Created by sunyifeng on 17/9/24.
 */
public class Test {
    public static void main(String[] args) {
        try {
            Service service = new Service();
            // 线程A
            ThreadA threadA = new ThreadA(service);
            threadA.setName("a");
            threadA.start();
            Thread.sleep(0);
            // 线程B
            ThreadB threadB = new ThreadB(service);
            threadB.setName("b");
            threadB.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
运行结果:

thread name:a,当前时间:1507651297645
Exception in thread "a" thread name:a,当前时间:1507651298658
java.lang.NumberFormatException: For input string: "a"
Thread B run time = 1507651298658
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at cha02.execise09.Service.testMethod(Service.java:14)
at cha02.execise09.ThreadA.run(ThreadA.java:16)

程序分析:

1、当某个线程出现异常时,自动释放锁;

2、其他线程获取对象锁后,可继续执行。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值