gpt4 book ai didi

Java:并发修改异常

转载 作者:行者123 更新时间:2023-12-01 23:58:41 26 4
gpt4 key购买 nike

我在 for(Entry...) 循环中遇到错误,在调用 dfs() 后,它会显示并发修改异常。我不知道为什么会发生这种情况,即使visitedOrder 与foreach 循环无关。如何解决这个问题?

public TreeMap<Integer, Integer> DFS()
{
TreeMap<Integer, Integer> stack = new TreeMap<Integer, Integer>();
TreeMap<Integer, Integer> visitedOrder = stack;
for(int i = 1; i < graph[0].length-1; i++)
{
stack.put(i, 0);
}
for(Entry<Integer, Integer> vertex : stack.entrySet())
{
if(vertex.getValue() == 0)
dfs(vertex.getKey(), visitedOrder);
}
System.out.println(visitedOrder.values());
return visitedOrder;
}

public void dfs(int vertex, TreeMap<Integer, Integer> visited)
{
visited.put(vertex, order++);
int currVertex = vertex;
for(int i = vertex; i < graph[0].length-1;i++)
{
if(graph[vertex][i+1] == 1)
{
dfs(++currVertex, visited);
break;
}
currVertex++;
}
}

最佳答案

这是“Class ConcurrentModificationException”的 Javadoc:

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.

事实上,这正是您正在做的事情:修改您在“foreach”循环中使用的结构。

解决方法:

如果您认为您的设计是正确的,请替换一个简单的 for 循环:for (int i=0; i < myContainer.size(); i++) ...

关于Java:并发修改异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15238841/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com