synchronized锁解决了多线程访问的数据安全问题,但是如果线程A在执行的时候出现异常,那么此时等待队列中的就绪线程会不会执行同步块中的数据呢?
static class Test0422SyncExc{
static int a = 0;
public synchronized static void add() throws Exception {
for (;;) {
a++;
System.out.println(Thread.currentThread().getName());
System.out.println(a);
Thread.sleep(2000);
if(a==5){
throw new Exception();
}
}
}
public static void main(String[] args) throws InterruptedException {
new Thread(()-> {
try {
add();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
Thread.sleep(2000);
new Thread(()-> {
try {
add();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}
很明显,在线程0出现异常后,线程1会直接操作线程0正在访问但是发生异常的数据。