当前位置: 代码迷 >> J2SE >> 无聊测ArrayList安全性有关问题的时候写了一段代码出现出现下标越界
  详细解决方案

无聊测ArrayList安全性有关问题的时候写了一段代码出现出现下标越界

热度:65   发布时间:2016-04-23 20:28:45.0
无聊测ArrayList安全性问题的时候写了一段代码出现出现下标越界
public class ContainerSyn implements Runnable {

static List list = new ArrayList();

public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new ContainerSyn(), "Thread1");
Thread t2 = new Thread(new ContainerSyn(), "Thread2");
Thread t3 = new Thread(new ContainerSyn(), "Thread3");
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
System.out.println("list size is " + list.size());
}

public void run() {
for (int i = 0; i < 110; i++) {
list.add(i);
}
}
}

------解决方案--------------------
这有线程安全问题
------解决方案--------------------
线程不安全,直观的改进就是“list.add(i);”加锁
------解决方案--------------------
110这个数目,目测很难做成越界
要在某个数组扩充数组后,在对新数组赋值前
另一个线程也对某个数组扩充但大小没前一个大的情况下才可能越界
110这样小的数目很难做成越界
------解决方案--------------------
public class ContainerSyn implements Runnable {
private Object obj;
static List<Integer> list = new ArrayList<Integer>();

ContainerSyn(Object obj) {
this.obj = obj;
}

public static void main(String[] args) throws InterruptedException {
Object obj = new Object();
Thread t1 = new Thread(new ContainerSyn(obj), "Thread1");
Thread t2 = new Thread(new ContainerSyn(obj), "Thread2");
Thread t3 = new Thread(new ContainerSyn(obj), "Thread3");
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
System.out.println("list size is " + list.size());
}

@Override
public void run() {
for (int i = 0; i < 110; i++) {
synchronized (obj) {
list.add(i);
}
}
}
}
  相关解决方案