/** * 演示調用sleep方法,鎖是否釋放 */ public class SleepLock { private Object lock = new Object(); private class ThreadSleep extends Thread{ @Override public void run() { String threadName = Thread.currentThread().getName(); System.out.println(threadName + " will take the lock!"); try { synchronized(lock) { System.out.println(threadName + " is taking the lock!"); Thread.sleep(5000); System.out.println(threadName + "finish the work!"); } } catch (InterruptedException e) { e.printStackTrace(); } } } private class ThreadNotSleep extends Thread{ @Override public void run() { String threadName = Thread.currentThread().getName(); System.out.println(threadName + " will take the lock time = " + System.currentTimeMillis()); synchronized(lock) { System.out.println(threadName + " is taking the lock time = " + System.currentTimeMillis()); System.out.println(threadName + " finish the work!"); } } } public static void main(String[] args) { SleepLock sleepTest = new SleepLock(); Thread threadA = sleepTest.new ThreadSleep(); threadA.setName("ThreadSleep"); Thread threadB = sleepTest.new ThreadNotSleep(); threadB.setName("ThreadNotSleep"); threadA.start(); try { Thread.sleep(1000); System.out.println(" Main slept!"); } catch (InterruptedException e) { e.printStackTrace(); } threadB.start(); } }
演示調用sleep方法,鎖是否釋放
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.