简单实现自己的显示锁

实现的目标

实现自己的锁,使线程同步。提供了两个lock方法一个带有参数(timeout)当固定时间内没有执行的线程就不让他去执行了。
1.创建接口 Lock定义了超时异常,当等待强锁的时间超过timeout让他超时异常

public interface Lock {
    class TimeoutException extends Exception{
        TimeoutException(String message){
            super(message);
        }
    }

    void lock() throws InterruptedException;

    void lock(long timeout) throws InterruptedException, TimeoutException;

    void unlock();
}

2.创建接口的实现类MyLock

定义有个waitSet来存放阻塞线程。定义isHold来决定是不是当前的锁已经被持有了。当isHold为true表示当前的显示锁被拿走了,其他线程就得等着进入waitSet队列。当线程拿到锁了,就立刻将isHold给置为true
在释放锁的时候就需要将所有线程notify()让其他线程争抢显示锁。(其实就是通过isHold中间变量来控制是不是拿到锁了!为什么不用volatile?肯定要给方法加锁防止逻辑乱掉,加锁方法里面就不用volatile了啊)

public class MyLock implements Lock {
    private boolean isHold = false;

    private final List<Thread> WAIT_SET = new LinkedList<>();

    private Thread currentThread;

    @Override
    public synchronized void lock() throws InterruptedException {

        while(isHold){
            this.wait();
            WAIT_SET.add(Thread.currentThread());
        }
        currentThread = Thread.currentThread();
        WAIT_SET.remove(Thread.currentThread());
        isHold = true;

    }

    @Override
    public synchronized void lock(long timeout) throws InterruptedException,TimeoutException {
        Long hasRmaining = timeout;
        Long endTime = System.currentTimeMillis() + timeout;
        while(isHold){
            if(hasRmaining <= 0)
            {
                throw new TimeoutException("超时异常");
            }
            WAIT_SET.add(Thread.currentThread());
            this.wait(timeout);
            hasRmaining = endTime - System.currentTimeMillis();
        }
        WAIT_SET.remove(Thread.currentThread());
        currentThread = Thread.currentThread();
        isHold = true;
    }

    public Collection getWitSet(){
        return Collections.unmodifiableCollection(WAIT_SET);
    }
    @Override
    public synchronized void unlock() {
        if(currentThread == Thread.currentThread()){
            isHold = false;
            this.notifyAll();
        }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值