For the object synchronous, asynchronous method, the design program must consider the whole problem, inconsistent data is a classic error.
1.demo
Public classMyThread4 {PrivateString user = "Liudan"; PrivateString pwd = "123456"; Private synchronized voidsetuservalue (string user, string pwd) { This. user =user; Try{Thread.Sleep (2000); } Catch(interruptedexception e) {e.printstacktrace (); } This. PWD =pwd; System.err.println ("SetValue end result->:user =" + user + "\ T" + "PWD =" +pwd); } Private voidGetuservalue () {System.err.println ("Getuservalue Setting Value: User =" + This. user + "\ T" + "PWD =" + This. pwd); } Public Static voidMain (string[] args)throwsinterruptedexception {FinalMyThread4 TUser =NewMyThread4 (); Thread Userthread=NewThread (NewRunnable () {@Override Public voidrun () {Tuser.setuservalue ("TestUser", "111111"); } }); Userthread.start (); Thread.Sleep (1000); Tuser.getuservalue (); }}
Description: The Set method adds the Synchronized keyword to the synchronization, the Get method gets not used to the Synchronized keyword, and finally to the thread start, a second after the thread, call the Get method again, verify whether the value is repaired.
Operation Result:
Getuservalue Setting Value: User = testuser pwd = 123456
SetValue Final Result->:user = Testuserpwd = 111111
1. First output the GET, after output set; After the thread starts, it modifies the user and then sleeps for 2 seconds:
Thread.Sleep (+);
, and then immediately
Thread.Sleep (+);
At this time the 1 seconds are contained in 2 seconds, the 1th second Get method (no synchronized) is called, the first two seconds to call the set method.
2.demo
Private synchronized void Getuservalue () { System.err.println (this. pwd); }
Operation Result:
SetValue Final Result->:user = testuser pwd = 111111
Getuservalue Setting Value: User = testuser pwd = 111111
1. Verify the release of the lock to ensure the authenticity of the data.
2. For a method flail lock, you need to consider the integrity of the functional business, while the set, get lock, use the Synchronized keyword, to ensure the atomicity of the business, otherwise there will be business errors.
Multithreading-Dirty Reads