gpt4 book ai didi

java - 任何人都可以解释如何在 java 中使用 Reentrant Lock over Synchronized 和一些最好的例子

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:20:38 24 4
gpt4 key购买 nike

当我在 http://javarevisited.blogspot.in/2013/03/reentrantlock-example-in-java-synchronized-difference-vs-lock.html 运行示例类时,我看到了与 synchronized 相同的行为。

最佳答案

这里有线程获取锁和释放锁的三种方式、方法。您可能想尝试使用 synchronized 关键字来实现这些。使用 ReentrantLock 的扩展功能和优势将变得显而易见。

public class DoorLockUsingLock {

private int counter= 0;
private Thread owner= null;
private Lock l = new ReentrantLock();
private Condition notLocked= l.newCondition();

public void lockItDown() throws InterruptedException {
l.lockInterruptibly();
try {
while ((counter> 0) && (owner!= Thread.currentThread())) {
notLocked.await();
}
counter++;
owner = Thread.currentThread();
} finally {
l.unlock();
}
}

public void lockItDownUninterruptibly() {
l.lock();
try {
while ((counter > 0) && (owner != Thread.currentThread())) {
notLocked.awaitUninterruptibly();
}
counter++;
owner= Thread.currentThread();
} finally {
l.unlock();
}
}

public boolean tryLockItDown(long timeout, TimeUnit unit) throws InterruptedException {
long time = unit.toNanos(timeout);
long end = System.nanoTime() + time;
boolean success = l.tryLock(timeout, unit);
if (!success) {
return false;
}
try {
time = end- System.nanoTime();
while ((counter> 0) && (owner != Thread.currentThread()) && (time > 0)) {
notLocked.await(time, TimeUnit.NANOSECONDS);
time = end - System.nanoTime();
}
if (time > 0) {
counter++;
owner = Thread.currentThread();
return true;
}
return false;
} finally {
l.unlock();
}
}

public void unlockIt() throws IllegalMonitorStateException {
l.lock();
try {
if (counter== 0) {
throw new IllegalMonitorStateException();
}
if (owner!= Thread.currentThread()) {
throw new IllegalMonitorStateException();
}
counter--;
if (counter == 0) {
owner = null;
notLocked.signal();
}
} finally {
l.unlock();
}
}
}

关于java - 任何人都可以解释如何在 java 中使用 Reentrant Lock over Synchronized 和一些最好的例子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18495438/

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