【发布时间】:2023-03-15 06:19:01
【问题描述】:
我只是在 4 核机器上运行一些多线程代码,希望它会比在单核机器上更快。想法是这样的:我有固定数量的线程(在我的情况下,每个核心一个线程)。每个线程执行一个Runnable 的形式:
private static int[] data; // data shared across all threads
public void run() {
int i = 0;
while (i++ < 5000) {
// do some work
for (int j = 0; j < 10000 / numberOfThreads) {
// each thread performs calculations and reads from and
// writes to a different part of the data array
}
// wait for the other threads
barrier.await();
}
}
在四核机器上,此代码在 4 个线程下的性能比在 1 个线程下的性能更差。即使有CyclicBarrier 的开销,我也会认为代码的执行速度至少应该快2 倍。为什么它运行慢?
编辑:这是我尝试过的繁忙等待实现。不幸的是,它使程序在更多内核上运行更慢(也在单独的问题here 中讨论):
public void run() {
// do work
synchronized (this) {
if (atomicInt.decrementAndGet() == 0) {
atomicInt.set(numberOfOperations);
for (int i = 0; i < threads.length; i++)
threads[i].interrupt();
}
}
while (!Thread.interrupted()) {}
}
【问题讨论】:
-
你能告诉 use 为什么你希望它在更多内核上运行得更快吗?
-
这表明每个线程都没有在单独的核心中运行,这是有道理的,因为您没有专门告诉它这样做(并且不能使用标准 Java 1.6)。
-
@Mat:线程越多,每个
Runnable的睡眠时间就越短。由于他们同时睡觉,他们应该更快地“醒来”。 -
@bestsss:既然这么琐碎,为什么不解释一下?
-
啊,好吧。然后这两者都不是,而是我的幽默类型。
标签: java multithreading