【发布时间】:2016-02-11 11:59:04
【问题描述】:
您好在这里定义了两个线程 EvenThread1 和 OddThread2。 EvenThread1 正在打印 ArrayList 中的偶数,并从列表中删除相应的值。相同的 OddThread2 也打印来自相同 ArrayList 的奇数和列表中相应的删除值。 问题是当我执行 2 或 3 次 java.util.ConcurrentModificationException 出现在控制台上时。 即使我正在使用有效检查从列表中删除该值。
if (j.intValue() >= 0)
{
it.remove();
}
我知道它为什么会出现,但我无法在这个程序中解决。 您能否建议我如何在以下程序中解决此异常并进行解释?
package MultiThreading;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Eg2
{
public static void main(String[] args)
{
new EvenThread1();
new OddThread2();
}
}
class EvenThread1 implements Runnable
{
List<Integer> list = Services1.getNum();
EvenThread1()
{
Thread th = new Thread(this);
th.start();
}
@Override
public void run()
{
Iterator<Integer> it = list.iterator();
while (it.hasNext())
{
Integer j = (Integer) it.next();
int a = j % 2;
if (a == 0)
{
System.out.println("Even: " + j.intValue());
if (j.intValue() >= 0)
{
it.remove();
System.out.println("List Data=" + list);
}
}
}
}
}
class OddThread2 implements Runnable
{
List<Integer> list = Services1.getNum();
OddThread2()
{
Thread th = new Thread(this);
th.start();
}
@Override
public void run()
{
Iterator<Integer> it = list.iterator();
while (it.hasNext())
{
Integer j = (Integer) it.next();
int a = j % 2;
if (a != 0)
{
System.out.println("Odd: " + j.intValue());
if (j.intValue() >= 0)
{
it.remove();
System.out.println("List Data=" + list);
}
}
}
}
}
abstract class Services1
{
static List<Integer> list = new ArrayList<Integer>();
static
{
for (int i = 0; i < 20; i++)
{
list.add(i);
}
}
static public List<Integer> getNum()
{
return list;
}
}
【问题讨论】:
-
实际上没有办法并行执行此操作。您需要同步访问列表,获取迭代器并删除偶数;然后同步对列表的访问,获取迭代器并删除奇数(或相反)。在两个线程中这样做是没有意义的,因为每个线程都需要独占访问列表。
标签: java multithreading arraylist