Java并发编程(五)让线程睡眠的 sleep 方法

逆流者 2021年02月21日 59次浏览

Thread类中有一个静态的sleep方法,当一个执行中的线程调用了Thread的sleep方法后,调用线程会暂时让出指定时间的执行权,也就是在这期间不参与CPU的调度,但是该线程所拥有的监视器资源,比如锁还是持有不让出的。指定的睡眠时间到了后该函数会正常返回,线程就处于就绪状态,然后参与CPU的调度,获取到CPU资源后就可以继续运行了。如果在睡眠期间其他线程调用了该线程的interrupt() 方法中断了该线程,则该线程会在调用 sleep 方法的地方抛出 InterruptedException 异常而返回。

sleep 会暂时放弃cpu的执行权, 但不会释放锁

public class SleepTest {

    /** 创建一个独占锁 */
    private static final Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try {
                    System.out.println("child threadA is in sleep");

                    Thread.sleep(10000);

                    System.out.println("child ThreadA is in awake");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        });

        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try {
                    System.out.println("child threadB is in sleep");

                    Thread.sleep(10000);

                    System.out.println("child threadB is in awake");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        });

        threadA.start();
        threadB.start();
    }
}
child threadA is in sleep
child ThreadA is in awake
child threadB is in sleep
child threadB is in awake

睡眠中的线程被其他线程中断会抛出InterruptedException 异常

public class SleepTest2 {

    public static void main(String[] args) throws InterruptedException {
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("child threadA is in sleep");

                    Thread.sleep(10000);

                    System.out.println("child ThreadA is in awake");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        // 启动线程
        threadA.start();

        // 主线程休眠2s
        Thread.sleep(2000);

        // 主线程中断子线程
        threadA.interrupt();
    }
}
child threadA is in sleep
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at base.thread.book.SleepTest2$1.run(SleepTest2.java:19)
	at java.lang.Thread.run(Thread.java:748)