One, the environment
Idea
Two. What is a thread safety issue and why is it wired security?
Thread-safety issues arise when multiple threads concurrently access shared resources (typically queries are not generated)
Three. For example
If I wanted to say a few Xunhua plus one, it would eventually increase to 1000. But 5 threads are required to add
classCountImplementsrunnable{Private intCount=1; Public voidrun () { while(count<=1000) {Count=count+1; System.out.println (Thread.CurrentThread (). GetName ()+ ", Count:" +count); } }} Public classThreadTest { Public Static voidMain (string[] args) {count Count=NewCount (); Thread T1=NewThread (count, "thread One")); Thread T2=NewThread (count, "thread two"); Thread T3=NewThread (count, "thread three"); Thread T4=NewThread (count, "thread four"); Thread T5=NewThread (count, "thread Five"); T1.start (); T2.start (); T3.start (); T4.start (); T5.start (); }}
Results:
The code shows that the maximum increase to 1000 loops will end then why does the 1001 appear!!
Since multithreading is now increasing, it is possible that when count is increased to 999, two threads enter the while loop, and then add two more times.
So how to solve it!!!
Four. Use locks to resolve 4.1 synchronous code blocks
classCountImplementsrunnable{Private volatile intCount=1; Private StaticObject OJ =NewObject (); Public voidrun () { while(count<=1000){ synchronized(OJ) {//OJ is the lock object can be any object or this if(count<=1000) {Count= Count + 1; System.out.println (Thread.CurrentThread (). GetName ()+ ", Count:" +count); } } } }} Public classThreadTest { Public Static voidMain (string[] args) {count Count=NewCount (); Thread T1=NewThread (count, "thread One")); Thread T2=NewThread (count, "thread two"); Thread T3=NewThread (count, "thread three"); Thread T4=NewThread (count, "thread four"); Thread T5=NewThread (count, "thread Five"); T1.start (); T2.start (); T3.start (); T4.start (); T5.start (); }}
4.2 Using the Synchronization method
classCountImplementsrunnable{Private volatile intCount=1; Private StaticObject OJ =NewObject (); Public voidrun () { while(count<=1000) {sole (); } } Public synchronized voidSole () {//This lock is the lock object that this if(count<=1000) {Count= Count + 1; System.out.println (Thread.CurrentThread (). GetName ()+ ", Count:" +count); } }} Public classThreadTest { Public Static voidMain (string[] args) {count Count=NewCount (); Thread T1=NewThread (count, "thread One")); Thread T2=NewThread (count, "thread two"); Thread T3=NewThread (count, "thread three"); Thread T4=NewThread (count, "thread four"); Thread T5=NewThread (count, "thread Five"); T1.start (); T2.start (); T3.start (); T4.start (); T5.start (); }}
Multithreading (b) multithreading Security and synchronization