// 模拟一些工作 Thread.sleep(5000); } catch (InterruptedException e) { System.out.println(Thread.currentThread().getName() + " was interrupted while waiting for the lock."); } finally { if (lock.isHeldByCurrentThread()) { lock.unlock(); System.out.println(Thread.currentThread().getName() + " released the lock."); } } }
publicsynchronizedvoiddoWork2() { try { System.out.println(Thread.currentThread().getName() + " acquired the lock."); Thread.sleep(5000); } catch (InterruptedException e) { System.out.println(Thread.currentThread().getName() + " was interrupted while waiting for the lock."); } finally { System.out.println(Thread.currentThread().getName() + " released the lock."); } }
则会输出
1 2 3 4 5
Thread-A acquired the lock. Thread-A released the lock. Thread-B acquired the lock. Thread-B was interrupted while waiting for the lock. Thread-B released the lock.