Introduction: Coordination between processes when two threads access the same resource using the same account and money
Solution: It is best to lock the process before accessing synchronized when it exclusively accesses the resource.Lock an object
Locking Process: One method is synchronized (locked), the other method is not synchronized, other threads can access the method that has not been synchronized, and affect the synchronized method. To protect the synchronization objects, all methods of the object to be accessed must be carefully considered for addition and deletion of synchronization, and the addition of synchronization efficiency becomes lower. Without synchronization, data inconsistency may occur.
Read and Write methods.
Both methods change the same value., Both methods should be synchronized.
Public class testsync implements runnable {<br/> timer = new timer (); <br/> Public static void main (string ARGs []) {<br/> testsync test = new testsync (); <br/> thread T1 = new thread (TEST); // two threads are created, one path is divided into two <br/> thread t2 = new thread (TEST); <br/> t1.setname ("T1"); <br/> t2.setname ("T2 "); <br/> t1.start (); <br/> t2.start (); <br/>}< br/> Public void run () {<br/> timer. add (thread. currentthread (). getname (); <br/>}</P> <p> class timer {<br/> Private Static int num = 0; <br/> Public void add (string name) {<br/> num ++; <br/> try {<br/> thread. sleep (1); <br/>}catch (interruptedexception e) {}< br/> system. out. println (name + ", you are the" + num + "thread using timer"); </P> <p >}< br/>Output:
T2, you are 1st threads using Timer
T1, you are the first thread to use Timer
Get rid of a piece of code
Class timer {<br/> Private Static int num = 0; // if it is changed to 1, 3 is displayed in the output. <br/> Public void add (string name) {<br/> synchronized (this) {// lock, you can lock the above num member variable <br/> num ++; <br/> try {<br/> thread. sleep (1); <br/>}catch (interruptedexception e) {}< br/> system. out. println (name + ", you are the" + num + "thread using timer"); <br/>}</P> <p >}< br/>}
The output is as follows:
T1, you are the first thread to use Timer
T2, you are 2nd threads using Timer