手写多线程Lock锁及ReentrantLock源码

package com.example.testdemo.test;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;

public class MyLock implements Lock{

    /**
     *公平锁:第一个线程获得锁后,第二个第三个来依次来获取锁,没有获取到时,会进入队列等待,当第一个线程unlock后,如果是公平锁(new ReentrantLock(true)),即按线程的顺序依次获得锁,
     * 如果是非公平锁(new ReentrantLock()默认是非公平锁)则是随机哪个程序获得锁,没有个先来后到的
     */
    //多线程并发调用: 0-未占用 >0-占用
    AtomicInteger state = new AtomicInteger();
    Thread ownerThread = null;
    LinkedBlockingDeque<Thread> waiters = new LinkedBlockingDeque();
    @Override
    public void lock() {
        if(!tryLock()){
            waiters.add(Thread.currentThread());//先入队列
            for(;;){
                if(tryLock()){
                    waiters.poll();//如果某一个线程抢到锁了,自己把自己从队列里挪出来
                    return;
                }else{
                    LockSupport.park();//2.等着  等待到何时执行? 唤醒的目的是继续抢锁
                }
            }
        }
    }

    @Override
    public boolean tryLock() {
        if(state.get()==0){
            //CAS底层c++实现 保证n个线程同时操作,只有一个能成功
            if(state.compareAndSet(0,1)){
                ownerThread = Thread.currentThread();
                return true;
            }
        }else if(ownerThread == Thread.currentThread()){//如果当前线程来获取锁,是可以获取到的,这里是可重入锁 (场景:递归修改目录下面的文件名称)
            state.addAndGet(1);
            return true;
        }
        return false;
    }

    @Override
    public void unlock() {

        if(ownerThread != Thread.currentThread()){
            throw new RuntimeException("非法调用,当前锁不属于你");
        }
        if(state.decrementAndGet()==0){//减1等于0 代表锁未占用
            ownerThread = null;
            //通知其他正在等待锁的线程
            Thread waiterThread = waiters.peek();//这里不从队列里删除,因为可能获取不到锁
            if(waiterThread!=null){
                LockSupport.unpark(waiterThread);//
            }
        }
    }

    @Override
    public Condition newCondition() {
        return null;
    }
    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }
    @Override
    public void lockInterruptibly() throws InterruptedException {

    }
}

//源码可以复制到自己本地看更方便

package com.example.testdemo.test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Lock;
public class ReentrantLockSource {

    private static final long serialVersionUID = 7373984872572414699L;
    /** Synchronizer providing all implementation mechanics */
    private final com.example.testdemo.test.ReentrantLockSource.Sync sync;

    /**
     * Base of synchronization control for this lock. Subclassed
     * into fair and nonfair versions below. Uses AQS state to
     * represent the number of holds on the lock.
     */
    abstract static class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = -5179523762034025860L;

        /**
         * Performs {@link Lock#lock}. The main reason for subclassing
         * is to allow fast path for nonfair version.
         */
        abstract void lock();

        /**
         * Performs non-fair tryLock.  tryAcquire is implemented in
         * subclasses, but both need nonfair try for trylock method.
         */
        final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();//获得当前线程
            int c = getState();//获取线程的状态
            if (c == 0) {
                if (compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0) // overflow
                    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;
        }

        protected final boolean isHeldExclusively() {
            // While we must in general read state before owner,
            // we don't need to do so to check if current thread is owner
            return getExclusiveOwnerThread() == Thread.currentThread();
        }

        final ConditionObject newCondition() {
            return new ConditionObject();
        }

        // Methods relayed from outer class

        final Thread getOwner() {
            return getState() == 0 ? null : getExclusiveOwnerThread();
        }

        final int getHoldCount() {
            return isHeldExclusively() ? getState() : 0;
        }

        final boolean isLocked() {
            return getState() != 0;
        }

        /**
         * Reconstitutes the instance from a stream (that is, deserializes it).
         */
        private void readObject(java.io.ObjectInputStream s)
                throws java.io.IOException, ClassNotFoundException {
            s.defaultReadObject();
            setState(0); // reset to unlocked state
        }
    }

    /**
     * Sync object for non-fair locks
     */
    static final class NonfairSync extends com.example.testdemo.test.ReentrantLockSource.Sync {
        private static final long serialVersionUID = 7316153563782823691L;


        final void lock() {
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }

        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
    }


    static final class FairSync extends com.example.testdemo.test.ReentrantLockSource.Sync {
        private static final long serialVersionUID = -3000897897090466540L;

        final void lock() {
            acquire(1);
        }

        /**
         * 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;
        }
    }

    public ReentrantLockSource() {
        sync = new com.example.testdemo.test.ReentrantLockSource.NonfairSync();
    }


    public ReentrantLockSource(boolean fair) {
        sync = fair ? new com.example.testdemo.test.ReentrantLockSource.FairSync() : new com.example.testdemo.test.ReentrantLockSource.NonfairSync();
    }

    public void lock() {
        sync.lock();
    }

    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    public boolean tryLock() {
        return sync.nonfairTryAcquire(1);
    }


    public boolean tryLock(long timeout, TimeUnit unit)
            throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(timeout));
    }


    public void unlock() {
        sync.release(1);
    }



}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值