package com.zx.lock;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
public class MyLock implements Lock {
//要维护1.当前是否有锁(保证能锁住),2.拿到锁的线程和3.已上锁的数量(保证可重入)
//判断当前是否有锁。
private volatile boolean isLock=false;
//拿到锁的线程。
private Thread lockedThread=null;
//已上的锁的数量。
private int lockCount;
@Override
public synchronized void lock() {
Thread currentThread = Thread.currentThread();
while(isLock && currentThread!=lockedThread){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
isLock=true;
lockedThread=currentThread;
lockCount++;
}
@Override
public synchronized void unlock() {
if(Thread.currentThread()==lockedThread){
lockCount--;
if(lockCount==0){
notifyAll();
isLock=false;
}
}
}
@Override
public void lockInterruptibly() throws InterruptedException {
// TODO Auto-generated method stub
}
@Override
public boolean tryLock() {
// TODO Auto-generated method stub
return false;
}
@Override
public Condition newCondition() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
// TODO Auto-generated method stub
return false;
}
}
java多线程与并发 - 自己实现一个简单的锁(实现Lock接口)
最新推荐文章于 2021-03-05 09:54:53 发布