synchronized重入後丟擲異常,鎖釋放了嗎
阿新 • • 發佈:2018-12-06
synchronized用於同步方法或者程式碼塊,使得多個執行緒在試圖併發執行同一個程式碼塊的時候,序列地執行。以達到執行緒安全的目的。
在多執行緒的時候是這樣的,但是對於單執行緒,是允許重入的,每重入一次,計數器加1,當退出程式碼塊時,計數器減1。
那正常退出時計數器減1,拋異常時計數器也是減1。那如果兩次重入,在內層丟擲異常,會釋放鎖嗎?還是隻會計數器減1,鎖並不會釋放?
直接上程式碼驗證:
public class SynchronizedTest1 { public static void main(String[] args){ Test test1= new Test(); Thread thread1 = new Thread(test1); Thread thread2 = new Thread(test1); thread1.start(); thread2.start(); } } class Test implements Runnable{ public synchronized void hello() throws Exception{ System.out.println(Thread.currentThread().getName()+ " say hello!!"); sorry(); System.out.println(Thread.currentThread().getName() + " helloed"); } public synchronized void sorry() throws Exception{ System.out.println(Thread.currentThread().getName() + " say sorry!!"); throw new Exception(Thread.currentThread().getName() + " this is a test!"); }public void run() { try { hello(); }catch (Exception e){ System.out.println(Thread.currentThread().getName() + " exception once"); } try { Thread.sleep(10000L); System.out.println(Thread.currentThread().getName() + " exit"); }catch (Exception e){ System.out.println(Thread.currentThread().getName() + " some exception"); } } }
Thread-0 say hello!! Thread-0 say sorry!! Thread-0 exception once Thread-1 say hello!! Thread-1 say sorry!! Thread-1 exception once Thread-1 exit Thread-0 exit Process finished with exit code 0
從以上執行結果,得出以下結論
結論:synchronized重入之後,丟擲異常,跳出synchronized程式碼塊,會釋放鎖。