To write thread safety concerns:
1. Shared variables
2. Variable variables
Sharing means that multiple threads can access at the same time, and variability means that their values can be changed in the lifecycle.
For example, the following count variables:
Copy Code code as follows:
Thread-Unsafe classes
public class Unsafecount {
private int count = 0; The variable is shared
public void Increase () {//There is no synchronization mechanism, multiple threads can access both
count++; The variable is variable
}
public int GetCount () {
return count;
}
}
There are 4 different ways to fix this problem:
1. The state variable is not shared in the thread, and the variable can be encapsulated into the method (the stateless object must be thread-safe) because the variable in the method is exclusive to each thread and is not shared with other threads. Like what:
Copy Code code as follows:
public int Add (int count) {
Return ++count;//This can also be said that stateless objects must be thread-safe
}
2. Modify the state variable to an immutable variable.
Copy Code code as follows:
Private final int count = 0;
3. Use the synchronization policy in the Access state variable.
Copy Code code as follows:
Public synchronized void Increase () {
count++;
}
4. Use atomic variable classes.
Copy Code code as follows:
Private Atomicinteger count;
public void Increase () {
Count.getandadd (1);
}