## 程序在执行过程中,如果出现异常,默认情况锁会被释放
package cn.qqjx.thread;
import java.util.concurrent.TimeUnit;
public class MyThread {
int count = 0;
synchronized void m() {
System.out.println(Thread.currentThread().getName() + " start");
while(true) {
count ++;
System.out.println(Thread.currentThread().getName() + " count = " + count);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(count == 5) {
int i = 1/0;
System.out.println(i);
}
}
}
public static void main(String[] args) {
MyThread t = new MyThread();
Runnable r = new Runnable() {
@Override
public void run() {
t.m();
}
};
new Thread(r, "t1").start();
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(r, "t2").start();
}
}
t1 start
t1 count = 1
t1 count = 2
t1 count = 3
t1 count = 4
t1 count = 5
t2 start
t2 count = 6
Exception in thread "t1" java.lang.ArithmeticException: / by zero
at cn.qqjx.thread.MyThread.m(MyThread.java:28)
at cn.qqjx.thread.MyThread$1.run(MyThread.java:40)
at java.lang.Thread.run(Thread.java:748)
t2 count = 7
t2 count = 8
t2 count = 9
t2 count = 10
t2 count = 11
t2 count = 12
t2 count = 13
t2 count = 14
t2 count = 15
t2 count = 16
t2 count = 17
t2 count = 18
t2 count = 19
t2 count = 20
t2 count = 21
t2 count = 22