1. Multi-threaded shared data
In multi-threaded operations, it is possible for multiple threads to process the same resource at the same time, which is shared data in multiple threads.
2. Thread synchronization
To resolve data sharing problems, you must use synchronization, which means that multiple threads can only have one thread executing the specified code during the same time period, and other threads will wait for the thread to finish before continuing.
Threads to synchronize, there are two ways to do this:
(1) Synchronizing code blocks
Synchronized (the object to synchronize) {
The operation to synchronize;
}
(2) Synchronization method
Public synchronized void Method () {
The operation to synchronize;
}
(3) Lock
3. Synchronization criteria
When writing synchronized fast, there are a few simple guidelines that can be followed to help avoid deadlocks and the risk of performance risks:
(1) Keep the code block short. Move the preprocessing and post-processing that do not follow the thread change out of synchronized fast.
(2) do not block. such as Inputstream.read ().
(3) Do not invoke methods on other objects while holding the lock.
Packagecom.vince;ImportJava.util.concurrent.locks.ReentrantLock;/*** Thread synchronization: 1. Synchronizing code blocks 2. Synchronization Method 3.Lock * Synchronization will sacrifice performance for security * *@authorAcer **/ Public classThreaddemo { Public Static voidMain (string[] args) {MyThread Mt=NewMyThread (); Thread T1=NewThread (MT); Thread T2=NewThread (MT); T1.start (); T2.start (); } Static classMyThreadImplementsrunnable{Private intFlag; PrivateObject obj=NewObject (); Public voidrun () {//Synchronizing code blocks synchronized(obj) {flag=0; System.out.println ("Start a meal" +flag); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO Auto-generated catch blockE.printstacktrace (); } Flag=1; System.out.println ("End of the meal" +flag); } } //synchronization method: A synchronized lock object is the current object Public synchronized voideat () {flag=0; System.out.println ("Start a meal" +flag); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO Auto-generated catch blockE.printstacktrace (); } Flag=1; System.out.println ("End of the meal" +flag); } Public synchronized voidmethod () {System.out.println ("Method2 ..."); } //Mutual exclusion Lock Private FinalReentrantlock lock=NewReentrantlock (); Public voidEat2 () {lock.lock ();//lockedFlag=0; System.out.println ("Start a meal" +flag); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO Auto-generated catch blockE.printstacktrace (); } Flag=1; System.out.println ("End of the meal" +flag); Lock.unlock ();//Unlock } }}
Java multi-Threading vs. concurrency-thread synchronization