java - 静态函数的线程安全

标签 java android multithreading static thread-safety

假设,我有像这样的静态 setter 和 getter:

private static List<String> result = new ArrayList<String>();

public static void setResult(String result) {
    result.add(result);
}

public static List<String> getResult() {
    return result;
}

public static void clearResult() {
    result.clear();
}

我想知道如果 setResult() 是从一个线程运行,getResult() 是从不同的线程调用,clearResult() 是从不同的线程调用,那么会发生什么?这个函数是线程安全的吗? getResult() 会返回正确的值吗?

还有一件事,如果我在中间调用 clearResult() 和持续检查 getResult() 的线程,它会得到正确的值吗??

如果不是那我该怎么办??

最佳答案

所有这三种方法都在 ArrayList 上运行,它不是线程安全的结构。因此,您的方法也不是线程安全的。来自 JavaDoc:

Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally.

以这种方式更改以下行,您应该没问题:

private static List<String> result = Collections.synchronizedList(new ArrayList<String>());

关于java - 静态函数的线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23005929/

相关文章:

javascript - 了解 JavaScript 的单线程特性

c# - 在多线程应用程序中使用 MessageBox 显示异常信息

java - 将 `TransformingRandomAccessList<T>` 转换为 `List<T>`

java - 错误 org.apache.pig.PigServer - 解析期间出现异常 : Error during parsing. 无法实例化

java - HTTP CURL 有效 - Java Jsoup 无效

android - 如何设计从右到左的线性布局

android - 增加一个整数变量?

android - ListView getItemViewType() 的复杂示例

c++ - 两个线程阻塞 I/O

java - Eclipse JDT 核心解析器不解析注释