java 同步中的线程出现异常会放弃锁吗

http://zhidao.baidu.com/question/374619544.html

实验证明:会
下面代码r1会抛出异常,但是r2仍能拿到o对象的锁

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();
			
	}

}
补充一点就是如果抛出异常被捕捉那么还是能继续获得锁第二个线程需等待线程一执行完毕才能执行

 

你可能感兴趣的:(JAVA)