什么是“原子”编程意味着什么? [英] What does "atomic" mean in programming?

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

问题描述

在Effective Java一书中,它指出:

In the Effective Java book, it states:


语言规范保证读取或写入
变量是原子的除非变量的类型为 long double [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 类型的变量。以下操作不是原子操作:

Here's an example, because an example is often clearer than a long explanation. Suppose foo is a variable of type long. The following operation is not an atomic operation:

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.

这样做的一个简单方法是制作变量volatile

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

private volatile long foo;

或同步每次访问变量:

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

private AtomicLong foo;

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

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