我是靠谱客的博主 无限灰狼,这篇文章主要介绍对list的线程不安全操作,现在分享给大家,希望可以做个参考。

对一个线程不安全的集合进行多线程操作, 并不会破单个元素的完整性, 根据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
29
public 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
28
public 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, 因为arraylist存在两个全局变量transient Object[] elementData; private int size; 而在多线程执行add方法时, 两个全局变量会出现线程安全问题. 当两个线程同时操作两个全局变量, 如果其中一个线程没有及时将当前缓存的内容刷新到共享内存中, 这个线程最后刷新的时候可能会覆盖其他已经修改的该位置的内容

复制代码
1
2
3
4
5
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; }



最后

以上就是无限灰狼最近收集整理的关于对list的线程不安全操作的全部内容,更多相关对list内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(63)

评论列表共有 0 条评论

立即
投稿
返回
顶部