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

来源:互联网 发布:傲游便携优化版 编辑:程序博客网 时间:2024/06/06 03:38

下面练习一下如下几个方法:
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
原创粉丝点击