假设,我有像这样的静态 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/