/**
* 演示调用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方法,锁是否释放
最新推荐文章于 2025-10-29 16:53:06 发布
本文通过两个Java线程的实例,演示了当一个线程调用sleep方法时,是否释放了同步锁。其中一个线程在获得锁后调用sleep方法暂停执行,另一个线程尝试在同一锁上获取资源。
170万+

被折叠的 条评论
为什么被折叠?



