Lock 之 tryLock

x33g5p2x  于2021-12-18 转载在 其他  
字(1.1k)|赞(0)|评价(0)|浏览(261)

tryLock 有两个重载的方法,分别如下:

boolean tryLock();
boolean tryLock(long time, TimeUnit unit) throws InterruptedException;

tryLock() 会立马返回一个布尔值,如果获得了锁就返回 true;如果没有获得锁就返回 false。无论是返回 true 还是 false,都会继续执行之后的代码。

tryLock(long time, TimeUnit unit) 会等待指定的时间,如果时间到了还没获得锁就返回 false;如果在时间范围内获得了锁就立刻返回 true,不用等待时间结束。无论是返回 true 还是 false,都会继续执行之后的代码。

我们来拿第二个方法进行测试,代码如下:

public class T03_ReentrantLock3 {
    Lock lock = new ReentrantLock();

    int count = 10;

    void m1() {
        try {
            lock.lock();
            for (int i = 0; i < count; i++) {
                TimeUnit.SECONDS.sleep(1);
                System.out.println(i + 1);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    void m2() {
        boolean tryLock = false;
        try {
            // 尝试在 5 秒内获得锁
            tryLock = lock.tryLock(5, TimeUnit.SECONDS);
            System.out.println("m2..." + tryLock);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (tryLock) {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        T03_ReentrantLock3 reentrantLock3 = new T03_ReentrantLock3();
        new Thread(reentrantLock3::m1).start();
        TimeUnit.SECONDS.sleep(1);
        new Thread(reentrantLock3::m2).start();
    }
}

控制台输出如下:

1
2
3
4
5
6
m2...false
7
8
9
10

我们把变量 count 变为 2 再进行测试,控制台输出如下:

1
2
m2...true
上一篇:可重入锁
下一篇:中断异常测试

相关文章