我正在学习多线程并发,发现在多线程环境下
但根据我的理解,这应该并行处理需要同样的时间。
你可以更改线程数。每个线程要做相同的工作量,因此在我的四核机器上,希望运行 4 个线程需要和单线程运行花费相同的时间。
我发现运行 4 个线程需要大约 2.3 秒,而单线程只需要 0.9 秒。
请问是否有什么误解?请帮助我理解这种行为。
对于线程数为4的情况,输出结果为:
Object.hashCode
的速度会变慢,同样数量的对象进行计算时,运行 4 个 threads
相对于 1 个 thread
,所需时间要多出一倍以上。但根据我的理解,这应该并行处理需要同样的时间。
你可以更改线程数。每个线程要做相同的工作量,因此在我的四核机器上,希望运行 4 个线程需要和单线程运行花费相同的时间。
我发现运行 4 个线程需要大约 2.3 秒,而单线程只需要 0.9 秒。
请问是否有什么误解?请帮助我理解这种行为。
public class ObjectHashCodePerformance {
private static final int THREAD_COUNT = 4;
private static final int ITERATIONS = 20000000;
public static void main(final String[] args) throws Exception {
long start = System.currentTimeMillis();
new ObjectHashCodePerformance().run();
System.err.println(System.currentTimeMillis() - start);
}
private final ExecutorService _sevice = Executors.newFixedThreadPool(THREAD_COUNT,
new ThreadFactory() {
private final ThreadFactory _delegate = Executors.defaultThreadFactory();
@Override
public Thread newThread(final Runnable r) {
Thread thread = _delegate.newThread(r);
thread.setDaemon(true);
return thread;
}
});
private void run() throws Exception {
Callable<Void> work = new java.util.concurrent.Callable<Void>() {
@Override
public Void call() throws Exception {
for (int i = 0; i < ITERATIONS; i++) {
Object object = new Object();
object.hashCode();
}
return null;
}
};
@SuppressWarnings("unchecked")
Callable<Void>[] allWork = new Callable[THREAD_COUNT];
Arrays.fill(allWork, work);
List<Future<Void>> futures = _sevice.invokeAll(Arrays.asList(allWork));
for (Future<Void> future : futures) {
future.get();
}
}
}
对于线程数为4的情况,输出结果为:
~2.3 seconds
线程数为1时,输出结果为
~.9 seconds