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、其他线程获取对象锁后,可继续执行。