I will give you the previous code first, you can run it yourself and give it a try:
public class Main {
public static void main(String[] args) {
// 用来测试的ArrayList
List<Object> list = new ArrayList<Object>();
// 线程数量(1000)
int threadCount = 1000;
// 用来让主线程等待threadCount个子线程执行完毕
CountDownLatch countDownLatch = new CountDownLatch(threadCount);
// 启动threadCount个子线程
for (int i = 0; i < threadCount; i++) {
Thread thread = new Thread(new MyThread(list, countDownLatch));
thread.start();
}
try {
// 主线程等待所有子线程执行完成,再向下执行
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
// List的size
System.out.println(list.size());
}
}
class MyThread implements Runnable {
private List<Object> list;
private CountDownLatch countDownLatch;
public MyThread(List<Object> list, CountDownLatch countDownLatch) {
this.list = list;
this.countDownLatch = countDownLatch;
}
public void run() {
// 每个线程向List中添加100个元素
for (int i = 0; i < 100; i++) {
list.add(new Object());
}
// 完成一个子线程
countDownLatch.countDown();
}
}
In the above code, a new non-thread-safe ArrayList is created in the main thread, and then 1000 threads are opened to add elements to this ArrayList respectively. Each thread adds 100 elements. After all threads are completed, the ArrayList What should the size be? Should be 100,000?
However, the actual running result may not be 100000! The result may be 99946, 99955... This is why non-thread-safe collections lead to incorrect results in the case of multi-threaded operations.
For specific thread safety, you can refer to a blog I wrote: http://xxgblog.com/2013/05/16/java-threa...
for (int i = 0, max = list.size(); i < max; i++) {
...
}
During the traversal process, thread B comes and deletes an element from the list. Then thread A will appear IndexOutOfBoundsException at the end of the traversal. Why, because the actual number of elements has become max - 1.
I will give you the previous code first, you can run it yourself and give it a try:
In the above code, a new non-thread-safe ArrayList is created in the main thread, and then 1000 threads are opened to add elements to this ArrayList respectively. Each thread adds 100 elements. After all threads are completed, the ArrayList What should the size be? Should be 100,000?
However, the actual running result may not be 100000! The result may be 99946, 99955... This is why non-thread-safe collections lead to incorrect results in the case of multi-threaded operations.
For specific thread safety, you can refer to a blog I wrote: http://xxgblog.com/2013/05/16/java-threa...
It will lead to data inconsistency, and the data obtained may be inaccurate. The impact is entirely under the control of your business logic
For example, thread A is traversing a List
During the traversal process, thread B comes and deletes an element from the list. Then thread A will appear IndexOutOfBoundsException at the end of the traversal. Why, because the actual number of elements has become max - 1.