![bb73abc3074f3d1ceafb1d968452706d.png](https://i-blog.csdnimg.cn/blog_migrate/214a30b9fb8bf22535a71032d5251ae5.jpeg)
Thread类中有一个静态的sleep方法,当一个执行中的线程调用了Thread的sleep方法后,调用线程会暂时让出指定时间的执行权,也就是在这期间不参与CPU的调度,但是该线程所拥有的监视器资源,比如锁还是持有不让出的。指定的睡眠时间到了后该函数会正常返回,线程就处于就绪状态,然后参与CPU的调度,获取到CPU资源后就可以继续运行了。如果在睡眠期间其他线程调用了该线程的interrupt()方法中断了该线程,则该线程会在调用sleep方法的地方抛出InterruptedException异常而返回。
下面举一个例子来说明,线程在睡眠时拥有的监视器资源不会被释放。
public class SleepTest {
private static ReentrantLock lock = new ReentrantLock();
public static void main(String[] args)
{
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
lock.lock();
try {
System.out.println("thread1 is sleeping start");
Thread.sleep(3000);
System.out.println("thread1 is sleeping over");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
lock.lock();
try {
// boolean b = lock.tryLock(1, TimeUnit.SECONDS);
System.out.println("thread2 is sleeping start");
Thread.sleep(3000);
System.out.println("thread2 is sleeping over");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
});
thread1.start();
thread2.start();
}
}
console
thread1 is sleeping start
thread1 is sleeping over
thread2 is sleeping start
thread2 is sleeping over
如上代码首先创建了一个独占锁,然后创建了两个线程,每个线程在内部先获取锁,然后睡眠,睡眠结束后会释放锁。首先,无论你执行多少遍上面的代码都是线程A先输出或者线程B先输出,不会出现线程A和线程B交叉输出的情况。从执行结果来看,线程A先获取了锁,那么线程A会先输出一行,然后调用sleep方法让自己睡眠10s,在线程A睡眠的这10s内那个独占锁lock还是线程A自己持有,线程B会一直阻塞直到线程A醒来后执行unlock释放锁。下面再来看一下,当一个线程处于睡眠状态时,如果另外一个线程中断了它,会不会在调用sleep方法处抛出异常。
public class SleepTest {
private static ReentrantLock lock = new ReentrantLock();
public static void main(String[] args)
{
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
lock.lock();
try {
System.out.println("thread1 is sleeping start");
Thread.sleep(3000);
System.out.println("thread1 is sleeping over");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
lock.lock();
try {
// boolean b = lock.tryLock(1, TimeUnit.SECONDS);
System.out.println("thread2 is sleeping start");
Thread.sleep(3000);
System.out.println("thread2 is sleeping over");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
});
thread1.start();
thread2.start();
thread1.interrupt();
}
}
console
thread1 is sleeping start
thread2 is sleeping start
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.tian.demo1.SleepTest$1.run(SleepTest.java:17)
at java.lang.Thread.run(Thread.java:745)
thread2 is sleeping over
子线程在睡眠期间,主线程中断了它,所以子线程在调用sleep方法处抛出了InterruptedException异常。
另外需要注意的是,如果在调用Thread.sleep(long millis)时为millis参数传递了一个负数,则会抛出IllegalArgumentException异常。