gpt4 book ai didi

Java 非重入锁实现

转载 作者:行者123 更新时间:2023-11-30 11:39:49 25 4
gpt4 key购买 nike

我已经实现了不可重入锁。我想知道这是否有任何错误、竞争条件等。我知道必须使用现有库(而不是编写我们自己的库)这一事实,但这只是为了看看我是否正确理解了 Java 并发性。感谢任何反馈。

public class MyLock {
private boolean isLocked = false;
private long owner = -1;
private static String TAG = "MyLock: ";

public synchronized void Lock() throws InterruptedException, IllegalStateException {
if(!isLocked) {
isLocked = true;
owner = Thread.currentThread().getId();

} else {
if(owner == Thread.currentThread().getId()) {
throw new IllegalStateException("Lock already acquired. " +
"This lock is not reentrant");
} else {
while(isLocked == true) {
System.out.println(TAG+"Waiting for Lock, Tid = " +
Thread.currentThread().getId());
wait();
}
}
}
System.out.println(TAG+"Lock Acquired: Owner = " + owner);
}

public synchronized void Unlock() throws IllegalStateException {
if(!isLocked || owner != Thread.currentThread().getId()) {
throw new IllegalStateException("Only Owner can Unlock the lock");
} else {
System.out.println(TAG+"Unlocking: Owner = " + owner);
owner = -1;
isLocked = false;
notify();
}
}

最佳答案

这里是 Java 中“标准”/“不可重入”锁的实现,作为 Java 内置 ReentrantLock 的包装器,可以简单地防止锁被多次获取。

/**
* A "non-reentrant" lock, implemented as a wrapper around Java's ReentrantLock.
*
*/
class StandardLock implements java.util.concurrent.locks.Lock {

public static class LockAlreadyHeldException extends RuntimeException {}

private final java.util.concurrent.locks.ReentrantLock mainLock;

private void checkNotAlreadyHeld() {
if (mainLock.getHoldCount()!=0) {
throw new LockAlreadyHeldException();
}
}

public StandardLock() {
mainLock=new java.util.concurrent.locks.ReentrantLock();
}

public StandardLock(boolean fair) {
mainLock=new java.util.concurrent.locks.ReentrantLock(fair);
}

@Override
public void lock() {
checkNotAlreadyHeld();
mainLock.lock();
}

@Override
public void lockInterruptibly() throws InterruptedException {
checkNotAlreadyHeld();
mainLock.lockInterruptibly();
}

@Override
public boolean tryLock() {
checkNotAlreadyHeld();
return mainLock.tryLock();
}

@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
checkNotAlreadyHeld();
return mainLock.tryLock(time, unit);
}

@Override
public void unlock() {
mainLock.unlock();
}

@Override
public Condition newCondition() {
return mainLock.newCondition();
}
}

这种方法的优点是该类实现了 Java 的 Lock 接口(interface),因此它附带了条件变量以允许创建监视器。为了充分利用并发编程的锁,监视器很重要。

关于Java 非重入锁实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13065994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com