gpt4 book ai didi

java - 内部锁和同步

转载 作者:行者123 更新时间:2023-11-29 04:35:20 24 4
gpt4 key购买 nike

我目前正在阅读 Intrinsic Locks and Synchronization在 oracle.com 上,我看到了这个特定的例子:

Synchronized statements are also useful for improving concurrency with fine-grained synchronization. Suppose, for example, class MsLunch has two instance fields, c1 and c2, that are never used together. All updates of these fields must be synchronized, but there's no reason to prevent an update of c1 from being interleaved with an update of c2 — and doing so reduces concurrency by creating unnecessary blocking. Instead of using synchronized methods or otherwise using the lock associated with this, we create two objects solely to provide locks.

public class MsLunch {
private long c1 = 0;
private long c2 = 0;
private Object lock1 = new Object();
private Object lock2 = new Object();

public void inc1() {
synchronized(lock1) {
c1++;
}
}

public void inc2() {
synchronized(lock2) {
c2++;
}
}
}

在本节之前,synchronized 方法解释如下:

public synchronized void increment() {
this.c++;
}

应该是这样的,如有错误请指正,同理

public void increment() {
synchronized(this) {
c++;
}
}

如果我不向 increment() 添加功能,是否正确?

我的问题现在来自短语:

but there's no reason to prevent an update of c1 from being interleaved with an update of c2

我不确定我是否完全理解“interleaved”在此上下文中的含义。这是否意味着,如果我从 MsLunch 示例中删除 lock2:

public class MsLunch {
private long c1 = 0;
private long c2 = 0;
private Object lock1 = new Object();
// private Object lock2 = new Object(); // 'lock2' is no more!

public void inc1() {
synchronized(lock1) {
c1++;
}
}

public void inc2() {
synchronized(lock1) { // Using 'lock1' here too
c2++;
}
}
}

我会遇到锁定问题吗?假设 thread-1 运行到 inc1(),从 lock1 获取锁但在能够递增或释放锁之前被挂起。现在 thread-2 正在进入 inc2(),其中为 lock1 创建了另一个锁。这是不是通过使用另一个 lock2 来避免的,这就是为什么我不会简单地使用 this 作为锁提供者的原因吗?或者换句话说:这会导致问题吗?

最佳答案

这里的两个锁只是为了有可能独立增加c1c2,而不是等到锁被释放。因此,如果 Thread-1 进入 c1 中的同步块(synchronized block)并获得一个 lock1,另一个 Thread-2 将能够当thread-1释放锁时不等待增加c2


重要提示:

使用 this 作为共享监视器有一个自身的问题,因为对 MsLunch 实例的引用在 MsLunch 之外是可见的。例如。 Thread-3 能够获取锁:synchronized (msLunchInstance) 在此类之外。

关于java - 内部锁和同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41875611/

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