java - 'nameList' 变量是实例变量还是类变量?为什么不包含在 'synchronised(this){}"语句中呢?

标签 java multithreading synchronization

我是 Java 的新手,正在尝试学习同步语句的概念。下面的代码和语句来自 Java tutorial Oracle .

我的问题是,“nameList”变量是实例变量还是类变量?为什么它不包含在 synchronized(this){} 语句中?我很难理解这个概念。

Synchronized Statements

Another way to create synchronized code is with synchronized statements. Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock:

public void addName(String name) {
    synchronized(this) {
        lastName = name;
        nameCount++;
    }
    nameList.add(name);
}

In this example, the addName method needs to synchronize changes to lastName and nameCount, but also needs to avoid synchronizing invocations of other objects' methods. (Invoking other objects' methods from synchronized code can create problems that are described in the section on Liveness.) Without synchronized statements, there would have to be a separate, unsynchronized method for the sole purpose of invoking nameList.add.

最佳答案

is the 'nameList' variable an instance variable or class variable?

你真的不需要知道。这无关紧要。

Why is it not included in the 'synchronised(this){}" statement?

因为必须假设 nameList.add() 已经是线程安全的,并且不需要在与其他两条指令相同的原子部分中将名称添加到列表中。

但我同意这是一个很糟糕的例子。

这是一个更简单的,希望更清楚:

public void addName(String name) {
    synchronized(this) {
        lastName = name;
        nameCount++;
    }
    System.out.println("a name has been added");
}

您希望以原子方式执行前两条指令。但是你不关心日志记录指令发生在这个原子操作之后。并且您希望在执行日志记录指令时避免阻止其他线程获取锁。 synchronized block 因此很有用:它使临界区尽可能短。使方法同步会使临界区比必要的更大。

关于java - 'nameList' 变量是实例变量还是类变量?为什么不包含在 'synchronised(this){}"语句中呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35480736/

相关文章:

java - 使用广度优先遍历算法,我按连续顺序将项目添加到二叉树中,但它们没有正确添加

java - 防止 AlertDialog 在 NeutralButton 单击时自动关闭???

java - 在服务器端查询http请求的困境

Java渲染循环和逻辑循环

c - pthread_mutex_trylock() 用于等待,直到其他锁尚未释放

java - 同步语句和独立的非同步方法

c++ - 在 C++ 中从另一个进程解锁线程

java - 使用 twitter4j 的 Oauth 中的问题

java - java中如何实现可停止和可取消的文件夹同步?

java - 如何在 Java 中通过 SSL 调用 Web 服务?