同步块内的线程抛出异常锁是否还在
2018-05-03 本文已影响164人
IAmWhoAmI
public class Test {
public static void main(String[] args) throws InterruptedException {
final Object o = new Object();
Runnable r1 = new Runnable() {
public void run() {
synchronized (o) {
throw new RuntimeException("throws");
}
}
};
Runnable r2 = new Runnable() {
public void run() {
synchronized(o) {
System.out.println("acquire lock");
}
}
};
new Thread(r1).start();
Thread.sleep(1000);
new Thread(r2).start();
}
}
运行结果:
Exception in thread "Thread-0" java.lang.RuntimeException: throws
at Test$1.run(Test.java:11)
at java.lang.Thread.run(Thread.java:748)
acquire lock
如果是lock 就不能这样:下面是错误的示例
public class Test {
public static void main(String[] args) throws InterruptedException {
final Object o = new Object();
final Lock lock =new Lock();
Runnable r1 = new Runnable() {
public void run() {
try {
lock.lock();
if(true)
throw new RuntimeException("throws");
lock.unlock();
}catch (Exception e){
}
}
};
Runnable r2 = new Runnable() {
public void run() {
synchronized(o) {
try {
System.out.println("开始");
lock.lock();
System.out.println("acquire lock");
lock.unlock();
}catch (Exception e){
}
}
}
};
new Thread(r1).start();
Thread.sleep(1000);
new Thread(r2).start();
}
}
正确的示例:所以一定要记得在finally 中释放锁。
public class Test {
public static void main(String[] args) throws InterruptedException {
final Object o = new Object();
final Lock lock =new Lock();
Runnable r1 = new Runnable() {
public void run() {
try {
lock.lock();
if(true)
throw new RuntimeException("throws");
}catch (Exception e){
}finally {
lock.unlock();
}
}
};
Runnable r2 = new Runnable() {
public void run() {
synchronized(o) {
try {
System.out.println("开始");
lock.lock();
System.out.println("acquire lock");
}catch (Exception e){
}finally {
lock.unlock();
}
}
}
};
new Thread(r1).start();
Thread.sleep(1000);
new Thread(r2).start();
}
}