Java多线程Lock对象常用方法(3)

下面练习一下如下几个方法:
isHeldByCurrentThread():查询当前线程是否保持此锁定
isFair():判断Lock是否为公平锁
isLocked():查询lock 是否被任意线程所持有。

package com.lenovo.plm.dms.p23;

import java.util.concurrent.locks.ReentrantLock;

public class Service {

    private ReentrantLock lock;

    public Service(boolean isfair){
        this.lock = new ReentrantLock(isfair);
    }

    public void service(){
        System.out.println("To check if the current thread hold the lock.."+lock.isHeldByCurrentThread());
        System.out.println("To check if it is a fair lock:"+lock.isFair());
        System.out.println("To check if the lock is locked by any thread."+lock.isLocked());
        lock.lock();
        System.out.println("To check if it is a fair lock:"+lock.isFair());
        System.out.println("To check if the current thread hold the lock.."+lock.isHeldByCurrentThread());
        System.out.println("To check if the lock is locked by any thread."+lock.isLocked());
        lock.unlock();
    }
}
package com.lenovo.plm.dms.p23;

public class Main {

    public static void main(String[] args) {
        final Service service = new Service(true);
        Runnable runnable = new Runnable(){
            @Override
            public void run() {
                // TODO Auto-generated method stub
                service.service();
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();

        final Service service2 = new Service(false);
        runnable = new Runnable(){
          @Override
            public void run() {
                // TODO Auto-generated method stub
                service2.service();
            }  
        };
        thread = new Thread(runnable);
        thread.start();
    }
}

运行结果:
To check if the current thread hold the lock..false
To check if it is a fair lock:true
To check if the lock is locked by any thread.false
To check if it is a fair lock:true
To check if the current thread hold the lock..true
To check if the lock is locked by any thread.true
To check if the current thread hold the lock..false
To check if it is a fair lock:false
To check if the lock is locked by any thread.false
To check if it is a fair lock:false
To check if the current thread hold the lock..true
To check if the lock is locked by any thread.true

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值