Lock的lock()与lockInterruptibly()

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/edc0228/article/details/81114273
public static void main(String[] args) throws InterruptedException {

    final Lock l = new ReentrantLock();
    Thread t1 = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                l.lockInterruptibly();
            } catch (InterruptedException e1) {
                e1.printStackTrace();
                System.out.println("t1异常");
            }

            System.out.println("t1拿到了锁,沉睡5秒");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                l.unlock();
            }
        }
    }, "t1");

    t1.start();

    // main线程睡一秒钟,为了让t1线程完成启动
    TimeUnit.SECONDS.sleep(1);

    Thread t2 = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                l.lockInterruptibly();
            } catch (InterruptedException e1) {
                e1.printStackTrace();
                System.out.println("t2被中断等待");
            }

            try {
                System.out.println("t2正在执行");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("t2异常");

            } finally {
                l.unlock();
            }
        }
    }, "t2");

    t2.start();

    // main线程睡一秒钟,为了t2线程完成启动
    TimeUnit.SECONDS.sleep(1);

    t2.interrupt();

}

结论:lock的lockInterruptibly方法能够中断正在等待获取锁的线程。

猜你喜欢

转载自blog.csdn.net/edc0228/article/details/81114273