sleep()函数是Thread类中的静态方法,调用了该方法的线程会让出一段时间的执行权,这段时间不会参与CPU调度.但是该线程所拥有的监视器资源,指定的睡眠时间到了之后该函数返回正常,线程处于就绪状态.如果在睡眠期间调用了interrupt(),会抛出IntermptedException 异常.
private static final Lock lock=new ReentrantLock();
public static void main(String[] args) {
Thread threadA = new Thread(() -> {
// 获取独占锁
lock.lock();
try {
System.out.println("child threadA is in sleep");
Thread.sleep(1000);
System.out.println("child threadA is in awaked");
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放锁
lock.unlock();
}
});
Thread threadB = new Thread(() -> {
// 获取独占锁
lock.lock();
try {
System.out.println("child threadB is in sleep");
Thread.sleep(1000);
System.out.println("child threadB is in awaked");
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放锁
lock.unlock();
}
});
threadA.start();
threadB.start();
}