我必须计算从1
到10000
的素数的数量,我将范围划分为8
个线程(numbers of my CPU cores
),因此每个线程必须检查1250
个号码。我不明白为什么在课程结束时我会这样做。得到这个作为输出:
numbers found: 0
的WorkerThread:
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class WorkerThread extends Thread {
private CyclicBarrier cyclicBarrier;
private PrimeNumber primeNumber;
private int min;
private int max;
public WorkerThread(CyclicBarrier cyclicBarrier, int min, int max,
PrimeNumber primeNumber) {
this.cyclicBarrier = cyclicBarrier;
this.primeNumber = primeNumber;
this.max = max;
this.min = min;
}
@Override
public void run() {
primeNumber.calculatePrimeNumber(min,max);
try {
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
primeNumber.printNumbers();
}
}
主要课程:
import java.util.concurrent.CyclicBarrier;
public class PrimeNumber {
private Integer totalPrimeNumber;
private int min;
private int max;
private int limit;
public PrimeNumber(int min, int max) {
totalPrimeNumber = new Integer(0);
this.min = min;
this.max = max;
}
public void calculatePrimeNumber(int min, int max) {
boolean found = false;
for (int i = min; i <= max; i++) {
for (int j = 3; j <= Math.sqrt(min); j++) {
if (min % 2 == 0)
break;
else if (min % j == 0) {
found = false;
break;
}
found = true;
}
if (found) {
totalPrimeNumber++;
}
}
}
public void printNumbers() {
synchronized (totalPrimeNumber) {
System.out.println("numbers found" + totalPrimeNumber);
}
}
public void setMin(int min) {
this.min = min;
}
public void setMax(int max) {
this.max = max;
}
public int getMin() {
return min;
}
public int getMax() {
return max;
}
private void setLimit(int max) {
this.limit = max;
}
private int getLimit() {
return limit;
}
public static void main(String args[]) {
int cores = Runtime.getRuntime().availableProcessors();
CyclicBarrier cyclicBarrier = new CyclicBarrier(cores);
PrimeNumber primeNumber = new PrimeNumber(1, 10000);
int numberToCheck = primeNumber.getMax() - primeNumber.getMin();
int numberToDivide = numberToCheck / cores;
primeNumber.setMin(1);
primeNumber.setLimit(primeNumber.getMax());
primeNumber.setMax(numberToDivide);
for (int i = 0; i < cores; i++) {
if (i == 7) {
primeNumber.setMax(primeNumber.getLimit());
WorkerThread workerThread = new WorkerThread(cyclicBarrier,
primeNumber.getMin(), primeNumber.getMax(), primeNumber);
workerThread.start();
} else {
WorkerThread workerThread = new WorkerThread(cyclicBarrier,
primeNumber.getMin(), primeNumber.getMax(), primeNumber);
workerThread.start();
primeNumber.setMin(primeNumber.getMax() + 1);
primeNumber.setMax(primeNumber.getMax() + numberToDivide);
}
}
}
}
答案 0 :(得分:2)
您只测试min
值
for (int j = 3; j <= Math.sqrt(min); j++) {
if (min % 2 == 0) // min never changes
break;
else if (min % j == 0)
您很可能打算在使用i
min
这是使用调试器或编写单元测试可以解决这个问题的地方。
我认为目的是看到大量的CPU被使用。如果你想要速度,你可以对它进行优化,但我怀疑一个线程中的Sieve of Eratosthenes会更快。