我听说适用于变量的规则在我们讨论数据结构时并不适用。这是真的吗?
例如,这个,非常好
public class SynchronizedCounter {
private int c = 0;
public synchronized void increment() {
c++;
}
public synchronized void decrement() {
c--;
}
public synchronized int value() {
return c;
}
}
并不意味着以下内容可以完美运行。
public class SynchronizedDataStructures {
private ArrayList<String> c = new ArrayList<String>();
public synchronized void add1(element) {
c.add(element);
}
public synchronized void clear1() {
c.clear();
}
public synchronized int value() {
return c;
}
}
这是真的吗?我该怎么做才能使其适用于数据结构?
最佳答案
如果将 add1(element)
更改为 add1(String element)
,并删除 value()
方法,则会编译,并且是线程安全的。
您将需要一种正确访问列表内容的方法。例如
public synchronized int value(int index) {
return c.get(index);
}
关于java - 如何确保数据结构的互斥?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29383168/