对一个线程不安全的集合进行多线程操作, 并不会破单个元素的完整性, 根据java内存模型可知,
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29public class TestCl { List<Integer> no = Collections.synchronizedList(new ArrayList<>()); //List<Integer> no = new ArrayList<>(); public static void main(String[] args) throws InterruptedException { TestCl t = new TestCl(); for(int i=0;i<10000;i++) { new Thread(t.new InnerThread(i)).start(); } TimeUnit.SECONDS.sleep(10); System.out.println(t.no.size()); } public class InnerThread implements Runnable{ Integer i; public InnerThread (Integer i) { this.i = i; } @Override public void run() { // TODO Auto-generated method stub no.add(i); } } }
对于同步的list, 输出结果是10000
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28public class TestCl { //List<Integer> no = Collections.synchronizedList(new ArrayList<>()); List<Integer> no = new ArrayList<>(); public static void main(String[] args) throws InterruptedException { TestCl t = new TestCl(); for(int i=0;i<10000;i++) { new Thread(t.new InnerThread(i)).start(); } TimeUnit.SECONDS.sleep(10); System.out.println(t.no.size()); } public class InnerThread implements Runnable{ Integer i; public InnerThread (Integer i) { this.i = i; } @Override public void run() { // TODO Auto-generated method stub no.add(i); } } }
复制代码
1
2
3
4
5public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; }
最后
以上就是无限灰狼最近收集整理的关于对list的线程不安全操作的全部内容,更多相关对list内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复