- sleep,yield 不释放锁
private synchronized void sleeping() {
System.out.println(Thread.currentThread() + "获取到了锁");
try {
Thread.sleep(2000);
System.out.println("休眠结束");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(Thread.currentThread() + "释放锁");
}
}
private static void testSleeping() {
ThreadStatusDemo demo = new ThreadStatusDemo();
for (int i = 0; i < 5; i++) {
new Thread(demo::sleeping).start();
}
}
public static void main(String[] args) {
testSleeping();
}
运行结果:

- wait释放锁
private synchronized void wait0() {
System.out.println(Thread.currentThread() + "成功获得锁,说明前一个线程已经释放了锁");
try {
wait(2000);
System.out.println(Thread.currentThread() + "休眠结束");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(Thread.currentThread() + "运行结束");
}
}
private static void testWait() {
ThreadStatusDemo demo = new ThreadStatusDemo();
for (int i = 0; i < 5; i++) {
new Thread(demo::wait0).start();
}
}
public static void main(String[] args) {
testWait();
}
运行结果:

网友评论