我目前正在做一个示例练习,我发现一个奇怪的观察结果,如果我用易失性程序替换 AutomicInteger ,则运行速度会更快。注意:我只进行读操作。
code:
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));
}
}
我的Runnable类:
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
该程序在我的机器上使用 volatile 运行所需的时间
所需总时间:66760
所需总时间:71773
这是否意味着对于读取操作, 易失性也比 AutomicInteger 更快?
AtomicInteger
在阅读上下文中基本上是一个薄包装volatile int
:
private volatile int value;
public final int get() {
return value;
}
public int intValue() {
return get();
}
不要期望包装器比单独的包装值更快。只能是跟...一样快 the volatile int
如果 JVM 使用内联。
并提示:如果你是“只进行读操作”,这会更快:
static final int integer= 100000000;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)