Problem description
After a lock is added to a non-final object using synchronized, the value (state) of the object is changed in the synchronized body (synchronous code block), which causes the thread to be unsafe, that is, the other thread gets the lock of the object after the change, thus entering the synchronization code block.
Scene design
Public classTestlockextendsthread{PrivateAAA AAA; PublicTestlock (AAA AAA) { This. AAA =AAA; } @Override Public voidrun () { This. Aaa.lockmethod (); } Public Static voidMain (string[] args) {AAA AAA=NewAAA (); Thread A1=NewTestlock (AAA); Thread A2=NewTestlock (AAA); A1.start (); Try{Thread.Sleep (500); } Catch(interruptedexception e) {e.printstacktrace (); } a2.start (); }} classaaa{PrivateBoolean lock =true; Public voidLockMethod () {synchronized(lock) {lock= !lock; Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (lock); } }}
Scenario Description
Two threads a1,a2, access the same AAA object AAA (Critical Resource), AAA in the LockMethod method is a synchronous code block, lock on the non-final lock object, in the synchronization code block change the value of the lock object. The 500ms sleep in the main function allows the thread to A1 the lock first, and the thread A1 accesses the synchronization code block, turns the lock value to False, and then sleeps for a second.
Assume
If the lock value changes do not affect the thread-safe features, then the thread A2 cannot get lock locks, after the end of hibernation, should output false, and then, the thread A2 get lock lock, enter the synchronization code block, the value of lock to True, and then sleep for a second, after the end of sleep, The value of the output lock is true, that is, the output of two values is false and true.
Program Run Results
True and True
Program Results Analysis
The first output is true, indicating that after the thread A1 into the synchronization code block, the value of lock is changed to false, into hibernation, the thread A2 can get the lock of the modified lock object, enter the synchronization code block, the value of lock becomes true, and then thread A2 into hibernation, After the thread A1 hibernation, the output is A2 modified by the thread after the lock value True, and then, after the thread A2 hibernation, the same output is true, conforming to the program output.
Summary and attention
For a lock on a non-object, when the state is modified in a synchronized code block, the thread is unsafe, that is, the other thread gets the lock on the modified object.
For an object that needs to be locked, it can be set to final, thus avoiding modifications to it, and if it is a non-final object, you need to avoid modifying the lock object in the synchronization block.
Changes in the state of the "Java" lock object can cause non-thread-safe