Each object has a flag lock. When a thread of an object accesses an object's synchronized data (including functions), the object is "locked" and the data declared as synchronized (including functions) cannot be called (because the current thread takes away the object's "Lock Flag").
The other threads of the same object can access the synchronized data only after the synchronized data is accessed by the front-end thread and the lock flag is released.
Note: Each class also has a "lock flag". For synchronized static data (including functions) can be locked under the whole class, avoiding the simultaneous access of static data.
We need to get a serial number for our business. The following is an example of a singleton pattern that obtains a serial number, using synchronized to constrain the get () function to avoid generating two identical serial numbers.
- Java source code for resource synchronization with synchronized
PackageCom.thread;/** * Use synchronized to avoid multithreading get duplicate serial number * @author Fan Fangming */ Public class easysynchronizedgetseq extends Thread { Private Static intNumber =0;Private StaticEasysynchronizedgetseq seq =NewEasysynchronizedgetseq (); Public Easysynchronizedgetseq(String name) {Super(name); }Private Easysynchronizedgetseq() { } PublicEasysynchronizedgetseqgetinstance() {returnSeq } Public synchronized int Get() {number++;//(a) returnNumber//(b)} Public void Run(){ for(inti =0; I <Ten; i + +) {intA = getinstance (). get ();//(1)System.out.println (Thread.CurrentThread (). GetName () +":"+ a);//Analog access Pause Try{Thread.Sleep (Ten); }Catch(Exception e) {E.printstacktrace (); } } } Public Static void Main(string[] args) {//Simple analog multithreading callEasysynchronizedgetseq SepA =NewEasysynchronizedgetseq ("A"); Sepa.start (); Easysynchronizedgetseq SEPB =NewEasysynchronizedgetseq ("---B"); Sepb.start (); Easysynchronizedgetseq SepC =NewEasysynchronizedgetseq ("======c"); Sepc.start (); }}
Run Results
A:1
-b:2
======c:3
A:4
-b:6
======c:5
-b:7
A:8
======c:9
A:11
======c:12
-b:10
======c:13
-b:15
A:14
-b:16
A:18
======c:17
A:20
-b:21
======c:19
-b:23
A:24
======c:22
-b:25
A:27
======c:26
A:29
-b:30
======c:28
to prove the error is easy, as long as there is a counter-case, but to prove that it is not easy, this requires a set of logic and support.
Therefore, this conclusion is only a general conclusion.
A good memory is better than a bad pen. 76-multithreading-synchronizing resources with synchronized