To achieve thread safety generally requires at least two features: Atomicity and Visibility.
Implementation method:
1) Use synchronize
: It is atomic and visible, so if the synchronize modified operation is used, then It comes with visibility, synchronized
uses pessimistic locking to achieve thread safety;
2) Use atomic classes instead of basic data types. Atomic classes use optimistic locks to achieve thread safety and multi-threading. To execute a in the environment, you can use the AtomicInteger
classincrementAndGet()
method to implement it. Volatile is also used to ensure visibility; use Unsafe
to call the native local methodCAS
, CAS uses bus locking or cache locking to ensure atomicity;
Recommended online video tutorial: java video tutorial
3) Using the volatile
keyword, volatile does not necessarily have atomicity. For example, using volatile-modified variables or -- operations (num), we need to make volatile-modified variables need to be atomic, then we can generally Set on the boolean
type variable, as follows:
volatile boolean tag = true; 线程1 while(tag){}; 线程2 while(tag){};
If there is a variable that increases or decreases, we can use the atomic class (AtomicInteger
).
4) Use ThreadLocal
to isolate each thread;
5) We can also use other locks, such as reentrant locks (ReentrantLock
) Ensure thread safety;
6) We can also use critical sections, mutexes, and semaphores to ensure thread safety.
This article is recommended by the java introductory learning column. Everyone is welcome to learn and communicate together.
The above is the detailed content of What are the ways to implement thread safety in java. For more information, please follow other related articles on the PHP Chinese website!