Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to master Synchronized

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to master Synchronized". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's take you to learn "How to master Synchronized"!

use

Synchronized keyword is one of the common means of thread synchronization in Java concurrent programming, and its role has three functions:

Mutual exclusion: ensure that threads mutually exclusive access synchronization generation, lock automatic release, multiple threads operating on the same code block or function must queue to obtain locks,

Visibility: Ensure that the modification of shared variables can be visible in time, and the thread that obtains the lock will refresh the data to the shared memory area after the operation is completed [1]

Orderability: Effective solution to reordering problems

There are three ways to synchronize:

modification instance method

modifying static methods

decorated code block

1. modification instance method

The synchronized keyword is used in front of the method to lock the method. In fact, the default lock is this object.

public class Thread1 implements Runnable{ //Shared resources (critical resources) static int i=0; //If there is no synchronized keyword, the output is less than 20000 public synchronized void increase(){ i++; } public void run() { for(int j=0;j

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report