自己动手写Concurrent锁工具2

2 篇文章 0 订阅

一、为什么1.5后会引入Concurrent包

其实应该这样说 Synchronized 有什么局限性:
  1. 不能一处加锁,另一处释放;
  2. 没有超时机制;
  3. 没有公平机制;
  4. 没有读写功能;
  5. 。。。
  • 严格的块结构
  • 活跃性问题
  • 改变锁的语义:重入性、读写保护、公平性
  • 访问控制

 

二、Java原生提供的锁工具有哪些

 

 

  • Synchronized
  • Object.wait()
  • Object.notify()
  • Object.notifyAll()

PS:JavaSynchronized是基于每线程而不是没调用

三、提供超时锁获取方式

/**
 * Created by xiejisheng on 18/5/31.
 */
public class Mutex {
    // JMM保证boolean语义的完整性,不保证可见性
    private volatile boolean inuse = false;

    public void acquire() throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();

        synchronized (this) {
            try {
                while (inuse)
                    wait();
                inuse = true;
            } catch (InterruptedException e) {
                notify();
                throw e;
            }
        }
    }

    public synchronized void release() {
        inuse = false;
        notify();
    }

    public boolean tryAcquire() throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();

        synchronized (this) {
            if (inuse)
                return false;
            else {
                inuse = true;
                notify();
                return true;
            }
        }
    }

    public boolean tryAcquire(long msecs) throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();

        synchronized (this) {
            if (!inuse) {
                inuse = true;
                return true;
            } else if (msecs <= 0) {
                return false;
            } else {

                long waitTime = msecs;
                long start = System.currentTimeMillis();
                try {
                    for (; ; ) {
                        wait(waitTime);

                        if (!inuse) {
                            inuse = true;
                            return true;
                        } else {
                            long end = System.currentTimeMillis();
                            waitTime = msecs - (end - start);
                            if (waitTime <= 0)
                                return false;
                        }
                    }
                } catch (InterruptedException ex) {
                    notify();
                    throw ex;
                }
            }
        }
    }
}

四、分析及问题

下一节会阐述Java原生锁工具的原理。

正确的道路就那么几条,而错误的方式千奇百怪,在编程的世界尤其如此。有时候你会不禁自问,什么样的奇葩竟会写出这么反人类的代码。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值