我有以下课程
public class Example{
public static List<String> list = new ArrayList<String>();
public static void addElement(String val){
synchronized(list){
list.add(val);
}
}
public static synchronized void printElement(){
Iterator<String> it = list.iterator();
while(it.hasNext()){
//print element
}
}
}
Run Code Online (Sandbox Code Playgroud)
在printElement方法中调用iterator()会抛出ConcurrentModificationException吗?基本问题是如果获取了类对象的锁(如在printElement方法中所做的那样),它是否也会锁定类成员/变量?请帮我解答.
是否对类进行锁定,也会锁定类变量? - java
你的锁是你的实例,而不是你的班级.不,它只锁定实例.
在printElement方法中调用iterator()会抛出ConcurrentModificationException吗?
如果该方法中的代码在迭代期间修改列表,则会出现这种情况.但是,如果该类中的所有代码也同步,并且您没有将该列表的引用提供给类之外的任何内容,那么您就知道只有该方法中的代码正在运行.
不过,你可能会更好,同步列表本身.这样,即使您已经给出了对列表的引用,假设所有使用它的代码都在其上进行同步,那么您将可以安全地使用并发mod:
public static void printElement(){
// ^--- No `synchronized ` here unless you REALLY need it for other reasons
synchronized (list) {
Iterator<String> it = list.iterator();
while(it.hasNext()){
//print element
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果你给了引用,并希望成为真正的肯定,无论是使用由返回一个列表Collections.synchronizedList,或从什么java.util.concurrent包.
| 归档时间: |
|
| 查看次数: |
112 次 |
| 最近记录: |