首先我们要知道如果两个线程之间是相互独立的,那么如果在一个线程执行过程中,发生异常,另外一个线程是不影响的,会继续执行。
那么,我们就思考,线程中发生了异常,所持有对象锁是如何变化。
public class Test171 {
synchronized public void show() {
for(int i = 0;i<10;i++) {
if(Thread.currentThread().getName().equals("tt")) {
if(i==5) {
Integer.parseInt("t");
}
}
System.out.println(Thread.currentThread().getName()+"这是show"+i);
}
}
}
public class Test172 {
public static void main(String[] args) {
Test171 t2 = new Test171();
Thread tt = new Thread(new MyThreadFour(t2));
Thread tt2 = new Thread(new MyThreadFour(t2));
tt.setName("tt");
tt2.setName("tt2");
tt.start();
tt2.start();
}
}
class MyThreadFour implements Runnable{
private Test171 t7;
public MyThreadFour(Test171 t7) {
super();
this.t7 = t7;
}
@Override
public void run() {
// TODO Auto-generated method stub
t7.show();
}
}
执行结果:
结论:出现异常的线程,会释放掉所持有的对象锁。