lock接口是什么意思_mutextrylock无效

lock接口是什么意思_mutextrylock无效正文开始前先把lock接口的源码摆出来(精简后的,特意保留了部分注释)publicinterfaceLock{/***Acquiresthelock.*/voidlock();/***Acquiresthelockunlessthecurrentthreadis*{@linkpl…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

正文开始前先把lock接口的源码摆出来(精简后的,特意保留了部分注释) 

public interface Lock {
    /**
     * Acquires the lock.
     */
    void lock();

    /**
     * Acquires the lock unless the current thread is
     * {@linkplain Thread#interrupt interrupted}.
     */
    void lockInterruptibly() throws InterruptedException;

    /**
     * Acquires the lock if it is free within the given waiting time and the
     * current thread has not been {@linkplain Thread#interrupt interrupted}.
     */
    boolean tryLock();

    /**
     * Acquires the lock if it is free within the given waiting time and the
     * current thread has not been {@linkplain Thread#interrupt interrupted}.
     */
    boolean tryLock(long time, TimeUnit unit) throws InterruptedException;

    /**
     * Releases the lock.
     */
    void unlock();

    /**
     * Returns a new {@link Condition} instance that is bound to this
     * {@code Lock} instance.
     */
    Condition newCondition();
}

(1)使用lock()

    和使用Synchronized关键字是一样的效果,直接去获取锁。成功了就ok了,失败了就阻塞等待了。不同的是lock锁是可重入锁,所以还是有不一样的地方:

  •  当锁可用,并且当前线程没有持有该锁,直接获取锁并把count set为1.
  •  当锁可用,并且当前线程已经持有该锁,直接获取锁并把count增加1.
  •  当锁不可用,那么当前线程被阻塞,休眠一直到该锁可以获取,然后把持有count设置为1.

 (2)使用tryLock()

  • 当获取锁时,只有当该锁资源没有被其他线程持有才可以获取到,并且返回true,同时设置持有count为1;
  • 当获取锁时,当前线程已持有该锁,那么锁可用时,返回true,同时设置持有count加1;
  • 当获取锁时,如果其他线程持有该锁,无可用锁资源,直接返回false,这时候线程不用阻塞等待,可以先去做其他事情;
  • 即使该锁是公平锁fairLock,使用tryLock()的方式获取锁也会是非公平的方式,只要获取锁时该锁可用那么就会直接获取并返回true。这种直接插入的特性在一些特定场景是很有用的。但是如果就是想使用公平的方式的话,可以试一试tryLock(0, TimeUnit.SECONDS),几乎跟公平锁没区别,只是会监测中断事件。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/181802.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号