JAVA Memory Model (synchronization of variables) and java model variable Synchronization
Modifications to variables in a thread may not be immediately visible to other threads, but may never be visible.
In code 1, if a thread calls MyClass. loop (), another thread calls MyClass at a certain time point in the future. setValue (100), the first thread may still not stop, and may continue forever
Code 1: public class MyClass {private static final String TAG = "MyClass"; private static int mValue = 0; public static void setValue (int n) {mValue = n ;} public static void loop () {int value; while (value! = 100) {try {Log. I (TAG, "Value is" + value); Thread. sleep (1000);} catch (Exception e ){}}}}
There are two solutions to the above problem:
First, use the synchronized keyword.
public class MyClass{ private static final String TAG="MyClass"; private static int mValue=0; public static synchronized void setValue(int n){ mValue=n; } public static synchronized int getValue(){ return mValue; } public static void loop(){ int value; while((value=getValue())!=100){ try{ Log.i(TAG,"Value is "+value); Thread.sleep(1000); }catch(Exception e){ } } }}
Second, use the volatile keyword
Public class MyClass {private static final String TAG = "MyClass"; private static volatile int mValue = 0; // Add the volatile keyword public static void setValue (int n) {mValue = n; // if it is mValue + = n, because it is not an atomic operation, you must use synchronized} public static void loop () {int value; while (value! = 100) {try {Log. I (TAG, "Value is" + value); Thread. sleep (1000);} catch (Exception e ){}}}}
Value ++ is not atomic, and value = 1 is atomic. The volatile keyword can only solve the concurrency problem where the variable declaration is atomic. If the variable is not atomic, you must use the synchronized keyword.
Do not call the method of another object in the synchronized block (it may have been locked and waiting for the object to be unlocked) unless you can ensure that no deadlock will occur, generally, only the code of the class of other objects can be manually written to the client to ensure that no deadlock will occur.