1 Star 0 Fork 24

ICY/concurrent-programming

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
ArrayListMultiThread.java 1.63 KB
一键复制 编辑 原始数据 按行查看 历史
ZHENFENGSHISAN 提交于 2017-05-04 15:58 +08:00 . ArrayList
package chapter2;
import java.util.ArrayList;
/**
* Created by 13 on 2017/5/4.
*/
public class ArrayListMultiThread {
static ArrayList<Integer> arrayList = new ArrayList<Integer>(10);
public static class AddThread implements Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p/>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see Thread#run()
*/
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
arrayList.add(i);
}
}
}
/**
* ArrayList是一个线程不安全的容器,多线程操作时会出现冲突,报错信息如下:
* Exception in thread "Thread-1" java.lang.ArrayIndexOutOfBoundsException: 22
* at java.util.ArrayList.add(ArrayList.java:441)
* at chapter2.ArrayListMultiThread$AddThread.run(ArrayListMultiThread.java:27)
* at java.lang.Thread.run(Thread.java:745)
*
* Vector是一个线程安全的容器,可以代替ArrayList
*
* @param args
* @throws InterruptedException
*/
public static void main(String args[]) throws InterruptedException {
Thread thread1 = new Thread(new AddThread());
Thread thread2 = new Thread(new AddThread());
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(arrayList.size());
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/javaIcy/concurrent-programming.git
git@gitee.com:javaIcy/concurrent-programming.git
javaIcy
concurrent-programming
concurrent-programming
master

搜索帮助