Modifications to variables in one thread may not be immediately visible to other threads, and in fact may never be visible.
In code one, if a thread calls Myclass.loop (), and another thread calls the Myclass.setvalue (100) at some point in the future, the first thread may still not terminate, possibly looping forever.
Code One: Public classmyclass{Private StaticFinal String tag="MyClass"; Private Static intMvalue=0; Public Static voidSetValue (intN) {Mvalue=N; } Public Static voidLoop () {intvalue; while(value!= -){ Try{log.i (TAG,"Value is"+value); Thread.Sleep ( +); }Catch(Exception e) {} }}}
There are two solutions to these problems:
One is to use the Synchronized keyword
Public classmyclass{Private StaticFinal String tag="MyClass"; Private Static intMvalue=0; Public StaticSynchronizedvoidSetValue (intN) {Mvalue=N; } Public StaticSynchronizedintGetValue () {returnMvalue; } Public Static voidLoop () {intvalue; while((Value=getvalue ())! = -){ Try{log.i (TAG,"Value is"+value); Thread.Sleep ( +); }Catch(Exception e) {} }}}
Second, using the volatile keyword
Public classmyclass{Private StaticFinal String tag="MyClass"; Private Static volatile intMvalue=0;//Add a volatile keyword Public Static voidSetValue (intN) {Mvalue=n;//if it's mvalue+=n, because it's not an atomic operation, you have to use synchronized . } Public Static voidLoop () {intvalue; while(value!= -){ Try{log.i (TAG,"Value is"+value); Thread.Sleep ( +); }Catch(Exception e) {} }}}
value++ are not atoms, value=1 are atoms. The volatile keyword only resolves those concurrency problems where the variable declaration is atomic and must use the SYNCHRONIZED keyword if the variable is not atomic
Do not invoke the method of another object in the synchronized block (it may have been locked and wait for the previously used object to be unlocked), unless you can guarantee that no deadlock will occur, and usually only the code of the class that wrote the other object will be able to determine that there is no deadlock.
Java's memory model (synchronization of variables)