【发布时间】:2013-10-26 02:18:27
【问题描述】:
我正在尝试并行化素数计数器作为练习。 我重构了原始代码并将长循环与其他循环分开,以便我可以并行化它们。 现在我有以下代码,多线程看起来很困难,因为我需要(按顺序)跟踪找到的素数并计算找到的素数。
nthPrime(long n) 获取要搜索的素数的数量。返回第 n 个素数。 count 是一个 ArryList
public static long nthPrime(long n) {
count.add((long) 1);
if (n < 2) {
count.add((long) 3);
return getCount();
}
count.add((long) 3);
if (n == 2) {
return getCount();
}
step = 4;
candidate = 5;
checker(n, step, candidate);
return getCount();
}
private static long checker(long n, int step, long candidate) {
while (count.size() < n) {
if (Checker.isPrime(candidate)) {
// checks the number for possible prime
count.add(candidate);
}
step = 6 - step;
candidate += step;
}
return getCount();
}
关于使用 util.concurrent 或线程来并行化的任何想法?
谢谢
【问题讨论】:
-
将我的multi-threading Sieve of Eratosthenes 从 C# 转换为 Java,将使工作程序达到合理的范围(在几个小时内达到 10^14)。诀窍是不要让多线程变得太细粒度,而是做(在那里)粗略的多线程,在这种情况下,每个线程的页面段。您的问题是您需要素数列表和计数,这意味着枚举素数,这意味着枚举它们的时间将比消除复合物的优化时间长得多。
标签: java multithreading java.util.concurrent