ReentrantLock显示锁

本文介绍了一个名为AttemptLocking的Java类,该类使用ReentrantLock实现两种不同的加锁方式:无时限尝试加锁(unTimed)和有时限尝试加锁(timed)。通过示例代码展示了如何在主线程及子线程中调用这些方法,并观察锁的获取情况。
摘要由CSDN通过智能技术生成
public class AttemptLocking {

    /*
     * public AttemptLocking() {
     * 
     * System.out.println("构造器初始化...");
     * }
     * 
     * {
     * System.out.println("init ...");
     * }
     * 
     * static {
     * System.out.println("static init ");
     * }
     */
    private ReentrantLock reentrantLock = new ReentrantLock();

    public void unTimed() {

        boolean captured = reentrantLock.tryLock();

        try {
            System.out.println("try lock:" + captured);
        } finally {
            // TODO: handle finally clause
            if (captured) {
                reentrantLock.unlock();
            }
        }
    }

    public void timed() {
        boolean captured = false;

        try {
            try {
                captured = reentrantLock.tryLock(2, TimeUnit.SECONDS);
                System.out.println("tryLock 2 Seconds " + captured);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } finally {
            // TODO: handle finally clause
            if (captured) {
                reentrantLock.unlock();
            }
        }

    }

    public static void main(String[] args) {
        final AttemptLocking attemptLocking = new AttemptLocking();
        attemptLocking.unTimed();
        attemptLocking.timed();
        new Thread() {

            {
                setDaemon(true);

            }

            @Override
            public void run() {

                attemptLocking.reentrantLock.lock();

                System.out.println("acquired");
            };

        }.start();
        Thread.yield();// give the 2nd task a chance只是给另一个线程一个机会,并不保证另一个线程一定能得到资源
        attemptLocking.unTimed();
        attemptLocking.timed();
    }

}
output:
 
  

try lock:true

 
  

tryLock 2 Seconds true

 
  

acquired

 
  

try lock:false

 
  

tryLock 2 Seconds false

 

 

 

 

 

 

转载于:https://www.cnblogs.com/zhangfengshi/p/9243245.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值