我想創建一個Erastosthenes Java程序的簡單並行Sieve,至少比我下面發佈的串行版本更有效一些。Java多線程 - Eratosthenes Sieve的基本並行示例
public void runEratosthenesSieve(int upperBound) {
int upperBoundSquareRoot = (int) Math.sqrt(upperBound);
boolean[] isComposite = new boolean[upperBound + 1];
for (int m = 2; m <= upperBoundSquareRoot; m++) {
if (!isComposite[m]) {
System.out.print(m + " ");
int threads=4;
for (int n=1; n<=threads; n++) {
int job;
if (n==1) {job = m * m;} else {job = (n-1)*upperBound/threads;}
int upToJob = n*upperBound/threads;
for (int k = job; k <= upToJob; k += m)
{
isComposite[k] = true;
}
}
}
}
for (int m = upperBoundSquareRoot; m <= upperBound; m++)
if (!isComposite[m])
System.out.print(m + " ");
}
我已經創建了一個循環來分割4個線程的工作。雖然我不知道如何從中創建實際的線程代碼。如何發送變量併爲每個線程啓動4個線程。
您可能想查看[Fork/Join](http://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html)框架。 –
我已更新我的問題。 –