“原子"是什么意思?在编程中是什么意思? [英] What does "atomic" mean in programming?

查看:65
本文介绍了“原子"是什么意思?在编程中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Effective Java 一书中,它指出:

In the Effective Java book, it states:

语言规范保证读或写一个变量是原子的,除非变量是 longdouble [JLS,17.4.7].

The language specification guarantees that reading or writing a variable is atomic unless the variable is of type long or double [JLS, 17.4.7].

在 Java 编程或一般编程的上下文中,原子"是什么意思?

What does "atomic" mean in the context of Java programming, or programming in general?

推荐答案

举个例子:假设 foo 是一个 long 类型的变量,那么下面的操作不是原子操作(在 Java 中):

Here's an example: Suppose foo is a variable of type long, then the following operation is not an atomic operation (in Java):

foo = 65465498L;

实际上,变量是使用两个单独的操作写入的:一个是写入前 32 位,第二个是写入后 32 位.这意味着另一个线程可能会读取 foo 的值,并查看中间状态.

Indeed, the variable is written using two separate operations: one that writes the first 32 bits, and a second one which writes the last 32 bits. That means that another thread might read the value of foo, and see the intermediate state.

使操作原子化包括使用同步机制以确保操作从任何其他线程被视为单个原子(即不可拆分成部分)操作.这意味着任何其他线程,一旦操作成为原子,要么在赋值之前,要么在赋值之后看到 foo 的值.但绝不是中间值.

Making the operation atomic consists in using synchronization mechanisms in order to make sure that the operation is seen, from any other thread, as a single, atomic (i.e. not splittable in parts), operation. That means that any other thread, once the operation is made atomic, will either see the value of foo before the assignment, or after the assignment. But never the intermediate value.

一个简单的方法是使变量可变一个>:

A simple way of doing this is to make the variable volatile:

private volatile long foo;

或者同步对变量的每次访问:

Or to synchronize every access to the variable:

public synchronized void setFoo(long value) {
    this.foo = value;
}

public synchronized long getFoo() {
    return this.foo;
}
// no other use of foo outside of these two methods, unless also synchronized

或者将其替换为 AtomicLong:

Or to replace it with an AtomicLong:

private AtomicLong foo;

这篇关于“原子"是什么意思?在编程中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆