Multi-threaded concurrent programming notes 03 (XiaoDi Classroom) --- Thread safety

 

 

 Atomic operations:

Such a piece of code.

Let’s output it:

We found that the results were not what we expected.

Normally it should output 1000.

This is because atomicity is not guaranteed.

So let's add atomicity:

This ensures our atomicity.

Next, let’s talk about this keyword in detail:

 

 

 I found that we output both instance objects at the same time.

So we can see that when we modify the ordinary method, we lock the instance object, not the class.

Modify static methods: modify the entire class

Call static methods.

 

This time, the method in the first thread is executed, and the method in the second thread is executed only after the sleep of the first thread ends.

 Decorate the code block:

 Modified code blocks also lock object instances. It is the object in synchronized brackets

volatile keyword and usage scenarios:

 

 Singleton and thread safety:

Hungry Chinese style:

 

Hungry style itself is thread-safe, so there is no need to perform locking and other operations.

Lazy man style:

We simulated the lazy singleton pattern in a time-consuming scenario:

We can see that each singleton instance object it returns is different, which is not the singleton effect we want.

It can also be seen from this that our lazy simple writing method is not thread-safe.

 

We only need to add the synchronized keyword to the returned method and run it again:

This will ensure our thread safety.

 But this way of writing is not the best way, because we lock the method. When there are multiple threads, other threads cannot call this method immediately, so it is also time-consuming.

We can add the synchronized keyword in another place and perform double verification:

 

However, there is a situation of instruction rearrangement in Java, so we have to make one step of modifications to achieve the best thread safety for lazy people:

We add the volatile keyword to the class, which can avoid instruction rearrangement.

How to avoid thread safety issues:

 

Guess you like

Origin blog.csdn.net/weixin_52618349/article/details/129765862