私は現在サンプル演習を行っていますが、AutomicInteger を揮発性プログラムに置き換えると、プログラムがより速く実行されるという奇妙な観察結果が 1 つ見つかりました。注:読み取り操作のみを行っています。
コード:
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));
}
}
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);
}
}
私のマシンで AutomicInteger を使用してこのプログラムを実行するのに必要な時間。
合計所要時間:102169
総所要時間:90375
私のマシンで揮発性を使用してこのプログラムを実行するのに必要な時間
合計所要時間:66760
総所要時間:71773
これは、読み取り操作でも volatile が AutomicInteger よりも高速であることを意味しますか?