ArrayList中的异常示例? [英] Example of exception in ArrayList?

查看:121
本文介绍了ArrayList中的异常示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ArrayList,我想要一个Exception的例子,如果多个线程试图访问相同的列表,而不同步?我在单线程应用程序中做到这一点,其中如果我们从列表中删除一个元素时,它抛出ConcurrentModificationExceptoin但我想在多线程环境中实现相同。如果任何人可以给我一个例子,将高度赞赏?

I am using ArrayList and I want an example of Exception in case if multiple threads try to access the same list without synchronization ? I done this in single threaded application in which if we remove an element from list while iteration it throws ConcurrentModificationExceptoin but I want to achieve the same in multi threaded environment. If anyone could give me an example of that would be highly appreciated ?

package com.test2;

public class ThreadTest extends Thread {

    List list = new ArrayList<String>();

    @Override
    public void run() {

        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        list.add("5");
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        list.add("6");
        list.add("7");
        list.add("8");

        Iterator<String> it = list.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }

    }

    public static void main(String[] args) {



        Thread th1 = new ThreadTest();
        Thread th2 = new ThreadTest();
        Thread th3 = new ThreadTest();
        th1.start();
        th2.start();
        th3.start();
        try {
            th1.join();
            th2.join();
            th3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }




    }

}


推荐答案

您正在每个线程中访问单独的列表实例。因为每个列表只能被一个线程访问,所以不能得到并发错误。

You're accessing a separate list instance in each of your threads. Since each list is only accessed by one thread, you can't get a concurrency error.

List list = new ArrayList<String>();

声明了一个实例字段。因此,每次调用 new ThreadTest()都会创建一个新的列表。为了使所有 ThreadTest 实例使用相同的列表,尝试使字段 static (即类字段)::

That declares an instance field. Therefore, each call to new ThreadTest() creates a new list. In order to make all the ThreadTest instances use the same list, try making the field static (i.e. a class field):

static List list = new ArrayList<String>();

至于如何可能会发生错误,请查看代码 ArrayList 添加方法

As for how an error can happen, take a look at the code for ArrayList's add method:

 public boolean add(E e) {
     ensureCapacityInternal(size + 1);  // Increments modCount!!
     elementData[size++] = e;
     return true;
 }



如果两个线程调用 add 同时,他们可以同时处理 elementData [size ++] = e 语句。 size 字段未声明 volatile ;因此,两个线程最终可以写入 elementData 数组中的同一个索引。

If two threads call add at the same time, they could process the elementData[size++] = e statement at the same time. The size field is not declared volatile; therefore, the two threads could end up writing to the same index in the elementData array.

即使 size 被声明为 volatile code> size ++ 操作是不是原子。请参阅 如何通过同时执行线程来破坏i ++的情况? 有关如何建模的示例如 size ++ 可能在多线程环境中失败。

Even if size were declared volatile, the size++ operation is not atomic. See How to model a situation, when i++ is corrupted by simultaneously executing threads? for an example of how an operation like size++ can fail in a multithreaded environment.

最后,如果你不明白 volatile 和在Java上下文中的原子意义,你真的需要在编写任何多线程代码之前阅读Java中的并发编程。这将是一个值得投资,因为你会通过理解这些概念,让自己很多头痛。

Finally, if you don't understand what volatile and atomic mean in the Java context, you really need to read up on concurrent programming in Java before you write any multithreaded code. It will be a worthwhile investment as you'll save yourself a lot of headaches by understanding these concepts.

这篇关于ArrayList中的异常示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆