对网上ArrayList线程不安全例子的不解,求解答

zy_116494718 2012-10-17 05:11:31
线程不安全的例子:

public class ArrayListInThread implements Runnable {
List<String> list1 = new ArrayList<String>(1);// not thread safe

// List<String> list1 = Collections.synchronizedList(new ArrayList<String>());// thread safe
public void run() {
try {
Thread.sleep((int)(Math.random() * 2));
}
catch (InterruptedException e) {
e.printStackTrace();
}
list1.add(Thread.currentThread().getName());
}

public static void main(String[] args) throws InterruptedException {
ThreadGroup group = new ThreadGroup("testgroup");
ArrayListInThread t = new ArrayListInThread();
for (int i = 0; i < 10000; i++) {
Thread th = new Thread(group, t, String.valueOf(i));
th.start();
}

while (group.activeCount() > 0) {
Thread.sleep(10);
}
System.out.println();
System.out.println(t.list1.size()); // it should be 10000 if thread safe collection is used.
}
}


我想问下为什么会出现结果不是10000的情况?
...全文
90 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

23,404

社区成员

发帖
与我相关
我的任务
社区描述
Java 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧