Thread ReentrantLock

1 限时锁 和 公平锁

2 代码实现

public class TimeLock implements Runnable{
    public static ReentrantLock reentrantLock = new ReentrantLock();
    public void run() {
        try {
            if (reentrantLock.tryLock(5, TimeUnit.SECONDS)) {
                Thread.sleep(6 * 1000);
            }else {
                System.out.println(Thread.currentThread().getName()+" get Lock Failed");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            // 查询当前线程是否保持此锁。
            if (reentrantLock.isHeldByCurrentThread()) {
                System.out.println(Thread.currentThread().getName()+" release lock");
                reentrantLock.unlock();
            }
        }
    }
    /**
     * 5秒后, 线程1不再加锁,线程2可以执行run。
     * 线程1 执行6秒, 线程2 不能加锁。
     */
    public static void main(String[] args) {
        TimeLock timeLock = new TimeLock();
        Thread thread1 = new Thread(timeLock, "thread1");
        Thread thread2 = new Thread(timeLock, "thread2");
        thread1.start();
        thread2.start();
    }
}
public class FairLock implements Runnable{
    public static ReentrantLock reentrantLock = new ReentrantLock(true);//按照队列执行
    @Override
    public void run() {
        while (true){
            try {
                reentrantLock.lock();
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName() + " getLock");
            }catch (InterruptedException e) {
            }
            finally {
                reentrantLock.unlock();
            }
        }
    }

    public static void main(String[] args){
        FairLock fairLock = new FairLock();
        Thread thread1 = new Thread(fairLock);
        Thread thread2 = new Thread(fairLock);

        thread1.start();
        thread2.start();
    }
}

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值