Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java中使用向量的并发崩溃_Java_Multithreading_Thread Safety - Fatal编程技术网

Java中使用向量的并发崩溃

Java中使用向量的并发崩溃,java,multithreading,thread-safety,Java,Multithreading,Thread Safety,我想我没有正确理解Java中的向量是同步的。 在我的代码中,一些线程正在运行修改向量的指令,例如调用mVector.addAll(另一个向量)。但我的应用程序在与以下代码交互向量时崩溃: // the vector declaration Vector<myClass> mVector = new Vector<myClass>; // the method that crashes public void printVector(){ for (myClas

我想我没有正确理解Java中的向量是同步的。 在我的代码中,一些线程正在运行修改向量的指令,例如调用mVector.addAll(另一个向量)。但我的应用程序在与以下代码交互向量时崩溃:

// the vector declaration
Vector<myClass> mVector = new Vector<myClass>;


// the method that crashes
public void printVector(){
    for (myClass mObject: mVector){
       System.out.println(mObject); 
    }
 }
//向量声明
向量mVector=新向量;
//崩溃的方法
public void printVector(){
对于(myClass移动对象:mVector){
系统输出打印项次(mObject);
}
}

如果向量对象是同步的,为什么会崩溃?我该怎么解决呢?提前感谢

您没有指定“崩溃”是什么意思,但是如果您得到一个
ConcurrentModificationException
则表示另一个线程在for each循环内修改了您的列表

此异常本身并不表示同步问题,因为它可以在单个线程中复制(只需在迭代时尝试向列表中添加元素)。而是在迭代集合时修改集合的结构时抛出。
迭代器是有状态的;在使用集合时修改集合会导致非常严重的错误,因此运行时会对其进行保护

要解决此问题,可以将for循环包装在同步块中:

synchronized (mVector) {
    for (... ) {
    }
}
阅读以下文件:

Vector的迭代器和listIterator方法返回的迭代器故障快速:如果在迭代器创建后的任何时间以任何方式(除迭代器自己的remove或add方法外)修改向量的结构,迭代器将抛出ConcurrentModificationException

该类是线程安全的,因为多个线程可以使用定义良好的行为同时读取/添加/删除元素

迭代器在sens中也是线程安全的,它们永远不会返回已删除或无效的元素


但这并不意味着您可以在从其他线程修改向量时对向量进行迭代。

同步向量并不意味着,它将使我们免于对同步的误解

import java.util.List;
import java.util.Vector;

public class Main {

  public static void main(final String[] args) {
    List<Integer> integers = new Vector<Integer>();
    for (int i = 0; i < 10; i++) {
      integers.add(i);
    }
    for (Integer integer : integers) {
      integers.add(1); // this will raise ConcurrentModificationException
      System.out.println(integer);
    }
  }

}
import java.util.List;
导入java.util.Vector;
公共班机{
公共静态void main(最终字符串[]args){
列表整数=新向量();
对于(int i=0;i<10;i++){
整数。加(i);
}
for(整数:整数){
integers.add(1);//这将引发ConcurrentModificationException
System.out.println(整数);
}
}
}
以上代码只需通过
ConcurrentModificationException
即可。原因是,上面的代码正在尝试迭代一个集合,此时它正在尝试更新自身。我们不可能同时做到这一点

如果您需要实现这样的目标,那么在完成迭代后,以某种方式标记/存储元素(例如:在列表中),并更新向量(以及任何集合)

编辑


确保
printVector()
方法在
mVector
的foreach块中被调用,以消除
ConcurrentModificationException

您所说的“崩溃”是什么意思?可能会提供更多关于崩溃的详细信息-堆栈跟踪/抛出异常。是的,很抱歉,我目前无法访问堆栈跟踪。是ConcurrentModificationException