volatile的int比AtomicInteger快

Ami*_*nde 4 java

我正在做一个示例练习,我发现一个奇怪的观察,如果我用挥发性程序替换AutomicInteger运行得更快.注意:我只做读操作.

码:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {

AtomicInteger integer  = new AtomicInteger(100000000);
// volatile int integer= 100000000;

public static void main(String[] args) {
// We will store the threads so that we can check if they are done
List<Thread> threads = new ArrayList<Thread>();
 long start = System.currentTimeMillis();
 Main main = new Main();
// We will create 500 threads

for (int i = 0; i < 500; i++) {
  Runnable task = new MyRunnable(main.integer);
  Thread worker = new Thread(task);
  // We can set the name of the thread
  worker.setName(String.valueOf(i));
  // Start the thread, never call method run() direct
  worker.start();
  // Remember the thread for later usage
  threads.add(worker);
}
int running = 0;
do {
  running = 0;
  for (Thread thread : threads) {
    if (thread.isAlive()) {
      running++;
    }
  }
  System.out.println("We have " + running + " running threads. ");
} while (running > 0);

System.out.println("Total Time Required :" +(System.currentTimeMillis()- start));
}
} 
Run Code Online (Sandbox Code Playgroud)

MyRunnable类:

 import java.util.concurrent.atomic.AtomicInteger;

public class MyRunnable implements Runnable {
private final AtomicInteger countUntil;

MyRunnable(AtomicInteger countUntil) {
    this.countUntil = countUntil;
}

@Override
public void run() {
    long sum = 0;
    for (long i = 1; i < countUntil.intValue(); i++) {
        sum += i;
    }
    System.out.println(sum);
}
}
Run Code Online (Sandbox Code Playgroud)

在我的机器上使用AutomicInteger运行此程序所需的时间.

所需时间总计:102169

所需时间总计:90375

在我的机器上使用volatile运行此程序所需的时间

所需时间总计:66760

所需时间总计:71773

这是否意味着volatile也比AutomicInteger更快地进行读操作?

Tom*_*icz 6

AtomicInteger在读取上下文中基本上是一个薄的包装volatile int:

private volatile int value;

public final int get() {
    return value;
}

public int intValue() {
    return get();
}
Run Code Online (Sandbox Code Playgroud)

不要指望包装器比单独包装的值更快.它只能是作为快volatile int,如果内联是由JVM使用.


并提示:如果你" 只做读操作 ",这将更快:

static final int integer= 100000000;
Run Code Online (Sandbox Code Playgroud)