Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - How to ensure the security of multithreading in java programs?
How to ensure the security of multithreading in java programs?
Three elements of concurrent programming (thread safety is embodied in):

Number of atoms: atoms, that is, particles that cannot be subdivided. Atomicity means that one or more operations are either all successful or all failed.

Visibility: The modification of variables by one thread can be immediately seen by another thread. (synchronous, changeable)

Orderliness: the order of program execution is consistent with the order of code execution. (The processor can reorder the instructions. )

Causes of thread safety problems:

Atomicity caused by thread switching

Visibility issues caused by caching

Orderliness problem caused by compilation optimization

Solution:

Atomic class, synchronization and locking at the beginning of JDK atom can solve the atomicity problem.

Synchronized, volatile and LOCK can solve the visibility problem.

Rules can solve the order problem before occurrence.