1、lock()最常用;
2、lockInterruptibly()方法一般更昂贵,有的impl可能没有实现lockInterruptibly(),只有真的需要效应中断时,才使用,使用之前看看impl对该方法的描述。

  • trylock
package lock;

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

public class GetLock_Demo {
    static Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        lock.lock(); //主线程拿到锁

        Thread th = new Thread(new Runnable() {
            @Override
            public void run() {
                boolean rs = lock.tryLock();
                System.out.println("是否获取到锁: " + rs);
            }
        });
        th.start();

        Thread.sleep(2000L);
        th.interrupt();//中断线程运行
        System.out.println("th 线程被中断了");
    }
}
  • trylock带超时
package lock;

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

public class GetLock_Demo {
    static Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        lock.lock(); //主线程拿到锁

        Thread th = new Thread(new Runnable() {
            @Override
            public void run() {
                boolean rs = false;
                try {
                    rs = lock.tryLock(1, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("是否获取到锁: " + rs);
            }
        });
        th.start();

        Thread.sleep(2000L);
        th.interrupt();//中断线程运行
        System.out.println("th 线程被中断了");
    }
}