/** * 演示调用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方法,锁是否释放
最新推荐文章于 2024-01-09 14:14:56 发布