并发编程学习之二:重入锁 ReentrantLock 的使用之限时等待

并发编程学习之一:重入锁 ReentrantLock 的使用

下面直接给出案例:

public class TimeLock implements Runnable {

    public static ReentrantLock lock = new ReentrantLock();

    private static final int NUM = 5;

    @Override
    public void run() {
        try {
            if (lock.tryLock(NUM, TimeUnit.SECONDS)) {
                System.out.println("等待前,"+Thread.currentThread().getName());
                Thread.sleep(3000);
                System.out.println("等待后,"+Thread.currentThread().getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        TimeLock t1 = new TimeLock();
        Thread thread1 = new Thread(t1);
        Thread thread2 = new Thread(t1);
        thread1.start();
        thread2.start();
    }
}

输出结果:

等待前,Thread-0
等待后,Thread-0
等待前,Thread-1
等待后,Thread-1

如上所示,拿锁需要等待5秒,5秒如果拿不到锁就不拿了,但是这里我等待了3秒,所以第二个线程是可以拿到锁的,我如果改成sleep 六秒,那么第二个线程就拿不到锁了,请看代码:

public class TimeLock implements Runnable {

    public static ReentrantLock lock = new ReentrantLock();

    private static final int NUM = 5;

    @Override
    public void run() {
        try {
            if (lock.tryLock(NUM, TimeUnit.SECONDS)) {
                System.out.println("等待前,"+Thread.currentThread().getName());
                Thread.sleep(6000);//这里有变化
                System.out.println("等待后,"+Thread.currentThread().getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        TimeLock t1 = new TimeLock();
        Thread thread1 = new Thread(t1);
        Thread thread2 = new Thread(t1);
        thread1.start();
        thread2.start();
    }
}

输出结果:

等待前,Thread-0
等待后,Thread-0

正如预料的一样,第二个线程就拿不到锁了。

 

以上的示例都来自于《java高并发程序设计(第二版)》,我是看了书照着书中的例子手敲了一下代码,加深一下印象,有兴趣的同学可以去看一下这本书,作者是葛一鸣,非常不错的书。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值