Sharing of
Multi-threaded operation of the same data, resulting in thread safety issues
Create a new class Sharedata
Design a member variable of type int count
Design a member Method Addcount (), put the count variable + +
Open multiple thread operations in the main function This member variable, in the main function
Get Sharedata object, new out
Use for loop 10 times, open threads in a loop, simulate 10 threads concurrently, within a loop
Get the Thread object, new out, constructor parameter: Runable Object
Anonymous inner class implements the Runable interface, overriding the Run () method
Call Thread.Sleep (1000) to make the thread sleep for one second, increasing the probability of a problem
Using the For loop 100 times, call the Addcount () method
Call Thread.Sleep (3), the main program sleeps for 3 seconds, to ensure that the above thread is all done
Print Count variable
Call the Start () method of the Thread object
PackageCom.tsh.mthread; Public classHome { Public intcount; Public Static voidMain (string[] args) {FinalHome Home =NewHome (); for(inti = 0; I < 10; i++) {Thread T=NewThread (NewRunnable () {@Override Public voidrun () { for(intj = 0; J < 100; J + +) {home.addcount (); } Try{Thread.Sleep (1000); } Catch(Exception e) {e.printstacktrace (); } System.out.println (Thread.CurrentThread ()+":"+home.count); } }); T.start (); } //sleep three seconds, wait up the top. Try{Thread.Sleep (3000); } Catch(Exception e) {e.printstacktrace (); } System.out.println ("Total:" +home.count); } Public voidAddcount () {count++; }}
Mutex compatibility
Use the Synchronized keyword to decorate the above Addcount () method, which adds locks while the current thread is operating, allowing only one visitor to access the resource with uniqueness and exclusivity
Public synchronized void Addcount () { count+ +; }
Decorating code blocks with synchronized
Public void Addcount () { synchronized (this) { count+ +; } }
[Javase] Watch Blogs learn java concurrency programming