How does java programming ensure the safety of multi-threaded operation?

Java programming is object-oriented, and the abstraction of objects is the class, so how to make the class thread-safe can ensure the thread safety of the program.

ps: What is the thread safety issue? Multiple threads operate shared variables at the same time, and these operations are not atomic operations

How to make the class thread safe?

  • Make the class stateless

There are no member variables in the class (neither static variables nor instance variables)

  • Privatize variable threads

The stack is private to the thread, so the local variables defined in the method are private to the thread 

ThreadLocal keeps a copy of the variable in each thread, and the copy is private to the thread 

  1. Stack closed
  2. ThreadLocal
  • Variables are decorated with private, and get and set methods are not provided
  • The get method provides a copy

       For example, there is now a get method that requires List<String> to be returned, then a new List can be created in the method, and the String object can be added to it.

  • Ensure that the operation is atomic (locking)
  1. synchronized keyword
  2. CASE
  3. Lock

Volatile can guarantee visibility and order, and is suitable for scenarios where one write and many reads 

  • Valotile keywords

 

Guess you like

Origin blog.csdn.net/qq_28411869/article/details/90018414