那个java原始整数(int)是原子的吗?两个共享一个int的线程的一些实验似乎表明它们是,但当然没有证据表明它们不是并不暗示它们是.
具体来说,我跑的测试是这样的:
public class IntSafeChecker {
static int thing;
static boolean keepWatching = true;
// Watcher just looks for monotonically increasing values
static class Watcher extends Thread {
public void run() {
boolean hasBefore = false;
int thingBefore = 0;
while( keepWatching ) {
// observe the shared int
int thingNow = thing;
// fake the 1st value to keep test happy
if( hasBefore == false ) {
thingBefore = thingNow;
hasBefore = true;
}
// …Run Code Online (Sandbox Code Playgroud)