ReentrantLock的四种加锁方式

java中使用显示的Lock对象时候必须被显示的创建,锁定和释放。因此它与内健的锁形式相比,代码缺乏优雅性,但是它也比较灵活。
*

 
* class X {
* private final ReentrantLock lock = new ReentrantLock();
* // ...
*
* public void m() {
* lock.lock(); // block until condition holds
* try {
* // ... method body
* } finally {
* lock.unlock()
* }
* }
* }
*

*
这里是jdk中的一个简单的使用方法。由此可见它的使用套路,能够捕获异常的优点。以上只是使用了lock方法去加锁,现在一一介绍它的加锁方式。

一、lock.lock();

If the lock is not available then the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired.

在等待获取锁的过程中休眠并禁止一切线程调度

二、void lockInterruptibly() throws InterruptedException;

If the lock is not available then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of two things happens:
The lock is acquired by the current thread; or Some other thread interrupts the current thread, and interruption of lock acquisition is supported.

在等待获取锁的过程中可被中断

三、boolean tryLock();

Acquires the lock if it is available and returns immediately with the value true. If the lock is not available then this method will return immediately with the value false.

获取到锁并返回true;获取不到并返回false

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

If the lock is available this method returns immediately with the value true. If the lock is not available then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of three things happens:The lock is acquired by the current thread; or Some other thread interrupts the current thread, and interruption of lock acquisition is supported; or The specified waiting time elapses.

然后运行代码看看
测试类如下

public class AttemptLocking {
    private ReentrantLock lock = new ReentrantLock();

    /**
     * 
     * @description
     * 
     */
    public void tLock() {
        lock.lock();
        try {
            System.out.println("mathod lock is not available");
            Thread.sleep(5000);
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            lock.unlock();
            System.out.println("mathod lock is available");

        }
    }

    /**
     * 
     * @description
     */
    public void tTryLock() {
        boolean captured = lock.tryLock();//
        try {
            if (captured) {
                System.out.println("mathod tryLock is not available");
                Thread.sleep(3000);
            } else {
                System.out.println("mathod tryLock is available--");
            }
        } catch (InterruptedException e) {
            System.out.println("mathod tryLock throw InterruptedExecption");
        } finally {
            if (captured) {
                lock.unlock();
                System.out.println("mathod tryLock is available");
            }
        }
    }

    /**
     * 
     * @description
     */
    public void tTryLock2() {
        boolean captured = false;
        try {
            captured = lock.tryLock(6, TimeUnit.SECONDS);
            if (captured) {
                System.out.println("mathod tryLock2 is not available");
            } else {
                System.out.println("mathod trylock2 is available++");
            }
        } catch (InterruptedException e) {
            System.out.println("mathod trylock2 throw InterruptedException");
        } finally {
            if (captured) {
                lock.unlock();
                System.out.println("mathod trylock2 is available");
            }
        }
    }

    public void tInterruptLock(){
        try {
            lock.lockInterruptibly();
            System.out.println("mathod interruptlock is not available");
            Thread.sleep(8000);
        } catch (InterruptedException e) {
            System.out.println("mathod interruptlock throw InterruptException");
        }finally{
            if(lock.isLocked()){
                lock.unlock();
                System.out.println("mathod interruptlock is available");
            }
        }
    }
}

调用类如下

public class Text{

 static Thread A=null;
 static Thread B=null;
public static void main(String[] args) {
        // TODO Auto-generated method stub
        final AttemptLocking al = new AttemptLocking();
        A=new Thread(new Runnable() {
            public void run() {
                //case1,2,3,4
                al.tLock();
            }
        });
        B=new Thread(new Runnable() {

            @Override
            public void run() {
                //case1
//              al.tLock();//等待的过程中调用中断不会中断,当进入时候调用中断会抛出中断异常的
                //case2
//              al.tTryLock();//可以修改睡眠时间为4s和6s,立即返回不用测试中断
                //case3
//              al.tTryLock2();//可以修改睡眠时间为4s和6s,等待的时候可以中断
                //case4
                al.tInterruptLock();//抛出中断异常
            }
        });
        A.setName("a");
        B.setName("b");
        A.start();
        B.start();
        //case1,3,4
//      B.interrupt();
    }
}

在指定时间内等待获取锁;过程中可被中断

假如线程A和线程B使用同一个锁LOCK,此时线程A首先获取到锁LOCK.lock(),并且始终持有不释放。如果此时B要去获取锁,有四种方式:

LOCK.lock(): 此方式会始终处于等待中,即使调用B.interrupt()也不能中断,除非线程A调用LOCK.unlock()释放锁。
LOCK.lockInterruptibly(): 此方式会等待,但当调用B.interrupt()会被中断等待,并抛出InterruptedException异常,否则会与lock()一样始终处于等待中,直到线程A释放锁。
LOCK.tryLock(): 该处不会等待,获取不到锁并直接返回false,去执行下面的逻辑。
LOCK.tryLock(10, TimeUnit.SECONDS):该处会在10秒时间内处于等待中,但当调用B.interrupt()会被中断等待,并抛出InterruptedException。10秒时间内如果线程A释放锁,会获取到锁并返回true,否则10秒过后会获取不到锁并返回false,去执行下面的逻辑。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值