1. Modified synchronized keyword or category code block;
2. Volatile keyword modified variables;
3. Add reentrant lock class
For example child: multiple threads in a process shared variable time, there will be thread-safety issues. (Corresponds to the operation of a plurality of windows ticket)
Non-synchronous state:
public static void main(String[] args){ Increase increase = new Increase(); int count = 10; while (count != 0){ new Thread(() -> { increase.increasementAndPrint(); }).start(); count --; } } static class Increase { private int i = 0; void increasementAndPrint() { System.out.print(i++ + "\n"); } }
This situation may lead to the same output i of the plurality of threads:
0
0
1
2
3
4
5
6
7
8
Use Sync:
1. Using the synchronized keyword // ensure atomicity and ordering static class Increase { private int i = 0; synchronized void increasementAndPrint() { System.out.println(i++); } } 2. Use the volatile // does not guarantee atomicity (a volatile variable is declared major visibility ordering) static class Increase { private volatile int i = 0; void increasementAndPrint() { System.out.println(i++); } }
The volatile keyword may not be able to guarantee the thread safety problems, in fact, in most cases volatile can guarantee thread-safety issues or variables. Therefore, in the case of the following two conditions are met, volatile can guarantee thread-safety issues variables:
- Result of the operation does not depend on the current value of the variable, or to ensure that only a single thread modifies the value of the variable.
3. Lock reentrant // ensure atomicity and ordering static class Increase { private ReentrantLock reentrantLock = new ReentrantLock(); private int i = 0; void increasementAndPrint() { reentrantLock.lock(); System.out.println(i++); reentrantLock.unlock(); } }