public class MyLock implements Lock {
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();
}
}
}
}
@Override
public void lockInterruptibly() throws InterruptedException {
}
@Override
public boolean tryLock() {
if(state.get() == 0){
if(state.compareAndSet(0,1)){
ownerThread = Thread.currentThread();
return true;
}
}
return false;
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return false;
}
@Override
public void unlock() {
if(ownerThread != Thread.currentThread()){
throw new RuntimeException("非法调用,当前锁不属于你");
}
if(state.decrementAndGet() == 0){
ownerThread = null;
Thread waiterThread = waiters.peek();
if(waiterThread != null){
LockSupport.unpark(waiterThread);
}
}
}
@Override
public Condition newCondition() {
return null;
}
}
测试:
public class TestMyLock {
static Lock lock = new MyLock();
public static void main(String[] args) throws InterruptedException {
lock.lock();
Thread th = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("start to get lock Interruptibly");
lock.lock();
System.out.println("拿到锁了");
lock.unlock();
System.out.println("释放锁了");
}
});
th.start();
Thread.sleep(100L);
lock.unlock();
}
}