日期:2014-05-20  浏览次数:20637 次

java 里面arraylist 是线程不安全的?这样的代码怎么解释
package com.test;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;

public class Test {
private List<String> muster=new ArrayList<String>();
public Test(){
Executors.newSingleThreadExecutor().execute(new Runnable(){
@Override
public void run() {
  try {
int i=1;
while(true){
muster.add(""+i);
System.out.println("放入数据 " + i++);
Thread.sleep(new Random().nextInt(1000));
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}});
Executors.newSingleThreadExecutor().execute(new Runnable(){
@Override
public void run() {
try {
while(true){
if(muster.size()>0){
System.out.println("移除数据 " + muster.remove(0));
}
Thread.sleep(new Random().nextInt(1000));
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}});

}

public static void main(String[] args) {

new Test();

}

}


------解决方案--------------------
探讨

引用:

存在线程安全问题
可是运行就是没有出问题

------解决方案--------------------
我说菜刀能把手剁了,你说你用了十几年没出事,这样的争论有意义吗?