05.线程在睡眠时拥有的监视器资源不会被释放(这里使用重入锁ReentrantLock)

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SleepDemo {
    //创建一个独占锁
    private static final Lock lock = new ReentrantLock();
    public static void main(String[] args) throws InterruptedException{
        //线程在睡眠时拥有的监视器资源不会被释放
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                //获取独占锁
                lock.lock();
                try {
                    System.out.println("threadA is in sleep");
                    Thread.sleep(10000);
                    System.out.println("threadA is in waked");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    //释放锁
                    lock.unlock();
                }
            }
        });
        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                //获取独占锁
                lock.lock();
                try {
                    System.out.println("threadB is in sleep");
                    Thread.sleep(10000);
                    System.out.println("threadB is in waked");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    //释放锁
                    lock.unlock();
                }
            }
        });
//        threadA.start();
//        threadB.start();
        //threadA is in sleep
        //threadA is in waked
        //threadB is in sleep
        //threadB is in waked
        //线程 A 先获取了锁,那么线程 A 会先输出一行,然后调用 sleep 方法让自己睡眠 10s,
        //在线程 A 睡眠的这 10s 内那个独占锁 lock 还是线程 A 自己持有,线程 B 会一直阻塞直到线程 A 醒来后执行 unlock 释放锁

        final Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("thread is in sleep");
//                    Thread.sleep(10000);
                    Thread.sleep(-1);
                    System.out.println("thread is in waked");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        Thread.sleep(2000);
        //主线程中断子线程
        //thread is in sleep
        //java.lang.InterruptedException: sleep interrupted
        thread.interrupt();
        //子线程在睡眠期间, 主线程中断了它,所以子线程在调用 sleep 方法处抛出了 InterruptedException 异常

        //sleep为负数
        //thread is in sleep
        //Exception in thread "Thread-2" java.lang.IllegalArgumentException: timeout value is negative
    }
}
posted @ 2019-08-16 09:08  fly_bk  阅读(288)  评论(0编辑  收藏  举报