gpt4 book ai didi

java - Bow/BowBack 线程锁解释

转载 作者:行者123 更新时间:2023-11-30 08:00:27 24 4
gpt4 key购买 nike

关于这个https://docs.oracle.com/javase/tutorial/essential/concurrency/newlocks.html

我们有一个我无法理解的 Bow/BowBack 示例,我想要详细解释到底发生了什么

确实,我删除了一些我不明白其用途的行:

    if (! (myLock && yourLock)) {
if (myLock) {
lock.unlock();
}
if (yourLock) {
bower.lock.unlock();
}
}

而且它仍然有效!

获取锁然后释放它的目的是什么,

在做这项工作之前?然后完成工作后再次释放!!

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.Random;
public class Safelock {
static class Friend {
private final String name;
private final Lock lock = new ReentrantLock();
public Friend(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public boolean impendingBow(Friend bower) {
Boolean myLock = false;
Boolean yourLock = false;
try {
myLock = lock.tryLock();
yourLock = bower.lock.tryLock();
} finally {
if (! (myLock && yourLock)) {
if (myLock) {
lock.unlock();
}
if (yourLock) {
bower.lock.unlock();
}
}
}
return myLock && yourLock;
}
public void bow(Friend bower) {
if (impendingBow(bower)) {
try {
System.out.format("%s: %s has"
+ " bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
} finally {
lock.unlock();
bower.lock.unlock();
}
} else {
System.out.format("%s: %s started"
+ " to bow to me, but saw that"
+ " I was already bowing to"
+ " him.%n",
this.name, bower.getName());
}
}
public void bowBack(Friend bower) {
System.out.format("%s: %s has" +
" bowed back to me!%n",
this.name, bower.getName());
}
}
static class BowLoop implements Runnable {
private Friend bower;
private Friend bowee;
public BowLoop(Friend bower, Friend bowee) {
this.bower = bower;
this.bowee = bowee;
}
public void run() {
Random random = new Random();
for (;;) {
try {
Thread.sleep(random.nextInt(10));
} catch (InterruptedException e) {}
bowee.bow(bower);
}
}
}
public static void main(String[] args) {
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
new Thread(new BowLoop(alphonse, gaston)).start();
new Thread(new BowLoop(gaston, alphonse)).start();
}
}

最佳答案

如果线程成功获取锁(或已经拥有锁),

tryLock() 返回 true。您不理解的代码会尝试获取两个 friend 的锁。如果至少其中一个无法获得:

if (! (myLock && yourLock)) {

然后它释放所获得的(如果有的话):

    if (myLock) {
lock.unlock();
}
if (yourLock) {
bower.lock.unlock();
}

因为该方法的重点是,如果两个锁都成功获得,则返回 true,如果两个锁均未成功获得,则返回 false,并且不持有任何锁。

关于java - Bow/BowBack 线程锁解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32024490/

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