并发中锁的理解

1:锁的原始概念


最原始的实现方式是用一个状态变量来控制是否进入,如果有已经在访问的,那么将运行的线程并入到一个池子里面,否则直接执行线程。在这个基本思路上衍生出好多同步需求来。
也就是说两个基本的变量,1: 状态量  2: 缓冲池

2:synchronized 系统自己实现了阻塞式队列同步算法。如果有一个线程出现问题,不能释放锁,会导致其他的线程同步出问题
对应的有非阻塞式的同步算法,也就是说一个线程出现挂掉,不影响其他线程挂掉,对应的是AtomicIntege

3:
而ReentrantLock 的实现也很经典
默认是非公平锁,
NonfairSync


        final void lock() {
            //尝试去竞争,如果成功,那么独占线程;如果失败,那么进入队列中排队		
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }


可以设置公平锁 FairSync


	//公平锁,直接将线程放入到队列中排队
        final void lock() {
            acquire(1);
        }




    public final void acquire(int arg) {
	//尝试获取锁,如果失败,那么已独占模式加入到队列中


        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
	    //同时线程进入中断状态	
            selfInterrupt();
    }




        /**
         * Fair version of tryAcquire.  Don't grant access unless
         * recursive call or no waiters or is first.
         */
        protected final boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            //获取控制变量的状态
	    int c = getState();
            if (c == 0) {
                //如果没有加锁,那么获取锁,同时设置为独占线程
                if (!hasQueuedPredecessors() &&
                    compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                //如果当前的线程还是独占线程,那么重入计数累加,可以看出这个锁是可重入锁
                int nextc = c + acquires;
                if (nextc < 0)
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }


        protected final boolean tryRelease(int releases) {
            int c = getState() - releases;
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
	    //多个可重入线程情况下,必须把锁释放干净才会返回真值
            boolean free = false;
            if (c == 0) {
                free = true;
                setExclusiveOwnerThread(null);
            }
            setState(c);
            return free;
        }






    private Node addWaiter(Node mode) {
        Node node = new Node(Thread.currentThread(), mode);
        // Try the fast path of enq; backup to full enq on failure
        //追加到尾部
	Node pred = tail;
        if (pred != null) {
            node.prev = pred;
            if (compareAndSetTail(pred, node)) {
                pred.next = node;
                return node;
            }
        }
        enq(node);
        return node;
    }




 //将线程结点加入到池中
 final boolean acquireQueued(final Node node, int arg) {
        boolean failed = true;
        try {
            boolean interrupted = false;
            for (;;) {
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return interrupted;
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }




    	
    public final boolean release(int arg) {
        if (tryRelease(arg)) {
            Node h = head;
            //如果释放锁成功,那么激活后面的一个线程
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }


    private void unparkSuccessor(Node node) {
        /*
         * If status is negative (i.e., possibly needing signal) try
         * to clear in anticipation of signalling.  It is OK if this
         * fails or if status is changed by waiting thread.
         */
        int ws = node.waitStatus;
        if (ws < 0)
            compareAndSetWaitStatus(node, ws, 0);


        /*
         * Thread to unpark is held in successor, which is normally
         * just the next node.  But if cancelled or apparently null,
         * traverse backwards from tail to find the actual
         * non-cancelled successor.
         */
        Node s = node.next;
        //从链表中获取结点,如果不成功,那么从尾部开始找
        if (s == null || s.waitStatus > 0) {
            s = null;
            for (Node t = tail; t != null && t != node; t = t.prev)
                if (t.waitStatus <= 0)
                    s = t;
        }
        //唤醒线程
        if (s != null)
            LockSupport.unpark(s.thread);
    }






4: wait和notify
wait也借用的是对象锁的概念,当调用wait的时候,会将对象锁,释放,然后降线程挂起到线程池中,在notify的时候随机从线程池中取得一个,然后唤醒

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值