Home > Java > javaTutorial > What are the functions of volatile variables in Java?

What are the functions of volatile variables in Java?

PHPz
Release: 2023-04-23 21:34:05
forward
836 people have browsed it

Explanation

1. When the program performs a reading operation or writing operation on a volatile variable, all changes to the previous operation must be made. The latter operation has been seen. The latter operation has not yet been performed.

2. When optimizing instructions, you cannot put the sentence for volatile variable access at the end, nor can you put the sentence for volatile variable access at the front.

General variables can only ensure that the method can obtain correct results in all places that rely on the authorization results during execution, but cannot guarantee that their order is consistent with the execution order of the program code.

Examples

volatile boolean initialized = false;
 
// 下面代码线程A中执行
// 读取配置信息,当读取完成后将initialized设置为true以通知其他线程配置可用
doSomethingReadConfg();
initialized = true;
 
// 下面代码线程B中执行
// 等待initialized 为true,代表线程A已经把配置信息初始化完成
while (!initialized) {
     sleep();
}
// 使用线程A初始化好的配置信息
doSomethingWithConfig();
Copy after login

What collection classes are there in Java

Collections in Java are mainly divided into four categories:

1, List List: ordered, repeatable;

2, Queue queue: ordered, repeatable;

3, Set collection: non-repeatable;

4, Map mapping: unordered, unique keys, non-unique values.

The above is the detailed content of What are the functions of volatile variables in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template