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 count variable:
//线程不安全的类
public class UnsafeCount {
private int count = 0; //该变量是共享的
public void increase() { //这里没有同步机制,多个线程可以同时访问
count++; //该变量是可变的
}
public int getCount() {
return count;
}
}
There are 3 ways to fix this problem:
1. Do not share the state variable in the thread, you can encapsulate the variable into the method (the stateless object must be thread safe), because the variables in the method are exclusive to each thread and are not shared with other threads. Like what:
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 void increase() {
count++;
}
Variable of multi-threaded concurrent programming