import java.util.concurrent.atomic.AtomicInteger;
public class ReentrantLockImpl {
private Thread lockThread;
private volatile boolean isLock;
private AtomicInteger lockCount = new AtomicInteger();
public int getLockCount() {
return lockCount.get();
}
public void lock() throws InterruptedException {
Thread currentThread = Thread.currentThread();
/**
* 如果不是同一个线程,并且锁标记为锁定状态,则当前线程等待
*/
while (lockThread != currentThread && isLock) {
synchronized (this) {
this.wait();
}
}
lockThread = currentThread;
lockCount.getAndIncrement();
isLock = true;
}
public void unlock() {
Thread currentThread = Thread.currentThread();
if (lockThread == currentThread) {
lockCount.getAndDecrement();
if (lockCount.get() == 0) {
isLock = false;
synchronized (this)
{
this.notify();
}
}
}
}
static class FOO implements Runnable {
ReentrantLockImpl lock;
public FOO(ReentrantLockImpl lock) {
this.lock = lock;
}
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName());
a();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void a() throws InterruptedException {
lock.lock();
System.out.println(lock.getLockCount());
b();
System.out.println(lock.getLockCount());
lock.unlock();
}
public void b() throws InterruptedException {
lock.lock();
System.out.println(11);
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
ReentrantLockImpl lock = new ReentrantLockImpl();
Thread t1 = new Thread(new FOO(lock));
// Thread t2 = new Thread(new FOO(lock));
t1.start();
// t2.start();
}
}
练习-可重入锁简单实现(Java实现)
猜你喜欢
转载自blog.csdn.net/q2365921/article/details/81096772
今日推荐
周排行