package com.test.threadlocal;
/**
* 发生异常会释放锁
* 实验场景:不进行捕获时,t1执行时发生异常,会释放锁,t2线程会执行;
* 对异常进行捕获后,t2线程不会执行
*/
public class ExceptionReleaseLock implements Runnable{
private int count = 0;
public void run() {
test();
}
private synchronized void test() {
while(true){
System.out.println(Thread.currentThread().getName() + "===========" + count);
count++;
try {
Thread.sleep(1000);
if(count == 5){
int i = 3/0;
}
}catch(Exception e){
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ExceptionReleaseLock erk = new ExceptionReleaseLock();
//t1线程和t2线程必须使用相同的对象erk,两个线程才能共享变量count
new Thread(erk,"t1").start();
new Thread(erk,"t2").start();
}
}