1. What is thread safety?
If a collection is thread-safe, then we don't have to consider concurrent access to this collection? (need to define their own Baidu, but difficult to understand)
2. Drill down to the level of thread safety in the JVM.
A invariant mode (basic types such as String)
b, absolute thread safety (regardless of how the processing is safe, the various methods used in various combinations are also safe.) )
C. Relative thread safety (that is, those collections, each synchronous method is safe separately)
3. A few examples of benefits (ArrayList thread insecure)
Packagethread-safe discussions;Importjava.util.ArrayList;classMyThreadImplementsrunnable{PrivateArraylist<integer> arry=NULL; PublicMyThread (arraylist<integer>Arry) { This. arry=Arry; } @Override Public voidrun () {//TODO auto-generated Method Stub for(inti=0;i<10;i++) {Arry.add (10); } System.out.println (Arry.size ()); } } Public classArraylisttest { Public Static voidMain (string[] args) {//TODO auto-generated Method StubArraylist<integer> arry=NewArraylist<integer>(); for(inti=0;i<100;i++) { NewThread (NewMyThread (Arry)). Start (); } }}
Very simple logic, a total of 100 threads, each add 10 number, the last size should be how much? 1000, congratulations, you have learned to count, you do the following look.
How many steps does it take to add an elephant to the refrigerator?
Arry.add () takes two steps. 1. Put it to the tail 2,size+1 two threads read the same tail, a loss is updated (the same as the lost updates in the database);
2.vector is not absolutely safe.
Packagethread-safe discussions;ImportJava.util.Vector;classAImplementsrunnable{PrivateVector<integer> a=NULL; PublicA (vector<integer>a) { This. a=A; } @Override Public voidrun () {//TODO auto-generated Method Stub intCount=0; while(count<10) {A.add (10); Try{Thread.Sleep (Long) (3000*math.random ())); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } System.out.println (A.size ()); Count++; } } } Public classVectortest { Public Static voidMain (string[] args) {//TODO auto-generated Method StubVector<integer> vec=NewVector<integer>(); for(inti=0;i<2;i++) { NewThread (NewA (VEC)). Start ();; } }}
There will be the same size after running, why? Both size and add are thread-safe, but together they are not thread-safe, if you add synchornized{add,size}; This is absolute thread safety.
Vector (relative thread safe) arrylist (thread insecure)