Resources:
http://xxgblog.com/2016/04/02/traverse-list-thread-safe/
Some list classes and their attributes
| Class |
Thread Safety |
Iterator |
Characteristics |
Description |
| Vector |
Is |
Fail-fast |
The internal method is modified with synchronized, so the execution efficiency is low |
1. A thread-safe list class does not mean that code that calls it is thread-safe
2. Only copyonwritearraylist can support the modification of the list elements over time |
| ArrayList |
Whether |
Fail-fast |
Improper use in multithreaded environments error prone |
| Collections.synchronizedlist |
Is |
Fail-fast |
Collections.synchronizedlist can get a thread-safe list, similar to vectors |
| Copyonwritearraylist |
Is |
Fail-Safe |
Each line enters upgradeable copies a copy and points the address to the new list, which is manipulated on the new list, so the final result may not be expected and is suitable for scenes that often need to traverse but rarely modify |
The following code simulates the performance of each class iterator mechanism in a multithreaded environment
Importjava.util.ArrayList;Importjava.util.Collections;Importjava.util.List;ImportJava.util.Vector;Importjava.util.concurrent.CopyOnWriteArrayList;ImportJava.util.concurrent.CountDownLatch;/** * http://xxgblog.com/2016/04/02/traverse-list-thread-safe/* * @Description: Multi-threaded Operation list*/ Public classThreadlisttest { Public voidMultiplethreadarraylist (FinalList<integer> list)throwsinterruptedexception {intCount = 10; for(inti = 0; I < count; i++) {list.add (i); } countdownlatch Countdownlatch=NewCountdownlatch (2); NewThread (NewRunnable () {@Override Public voidrun () {Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } for(integer integer:list) {System.out.println (integer); } countdownlatch.countdown (); }}). Start (); NewThread (NewRunnable () {@Override Public voidrun () {Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetId ()+ "Remove" + list.remove (0)); Countdownlatch.countdown (); }}). Start (); Countdownlatch.await (); } Public Static voidMain (string[] args)throwsinterruptedexception {threadlisttest test=Newthreadlisttest (); List<Integer>list; List=NewVector<> ();//vector only guarantees internal method thread safetyList =NewArraylist<> ();//ArrayList efficiency is more efficient than vector, but non-thread safeList = Collections.synchronizedlist (NewArraylist<> ());//Collections.synchronizedlist and Vector have the same wonderfulList =NewCopyonwritearraylist<> ();//copyonwritearraylist thread Safety: Each line enters upgradeable copies a copy and points the address to the new list and operates on the new list, so the final result may not match the expectedtest.multiplethreadarraylist (list); System.out.println (List.tostring ()); }}
Java multithreaded series five--list class