What you need to be interested in writing thread safety:
Shared variables
Variable variable
sharing means that multiple threads can be accessed at the same time, and mutable means that their values can change over the life cycle. For example, the following countvariables:
//线程不安全的类
public class UnsafeCount {
     private   Span class= "KWD" style= "Color:rgb (30,52,123)" >int count =   0      //the variable is a shared
     public   Span class= "KWD" style= "Color:rgb (30,52,123)" >void Increase () { //There is no synchronization mechanism, multiple threads can access simultaneously
count++; //该变量是可变的
}
     public   Span class= "KWD" style= "Color:rgb (30,52,123)" >int GetCount () {
return count;
}
}
There are 4 ways to fix this problem:
1. You can encapsulate a variable in a method without sharing the state variable in the thread (Stateless objects must be thread-safe)because the variables in the method are exclusive to each thread and are not shared with other threads. For example:
public   int add ( int count ) {
return ++count;//这里也可以说无状态的对象一定是线程安全的
}
2.Modify the state variable to a variable that is immutable.
private final int count = 0;
3. Use the synchronization policy in the Access state variable.
public   synchronized    Span class= "KWD" style= "Color:rgb (30,52,123)" >void Increase () {
count++;
}
4. Use the atomic variable class.
private atomicinteger count;public void Increase () {Count.getandadd (1);}
Variables for multithreaded concurrency programming in Java