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

What are the functions of volatile variables in Java?

PHPz
PHPzforward
2023-04-23 21:34:05779browse

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();

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete