我试图找出此问题的解决方案,但在StackOverflow上找不到它?
我只想知道为什么我的多线程实际上工作这么慢,所以应该做相反的事情。
public class Prime {
static BufferedWriter writer;
static DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
public static void main(String[] args) throws IOException {
System.out.println("Without Thread" + findPrime() + " ms");
System.out.println("With thread : " + findPrimeWithThreads() + " ms");
}
public static long findPrimeWithThreads() {
Instant start = Instant.now();
int primaryNumber = 3;
while (primaryNumber <= 100000) {
int finalPrimaryNumber = primaryNumber;
new Thread(() -> {
multiplicationHelper(finalPrimaryNumber);
}).start();
new Thread(() -> {
multiplicationHelper(finalPrimaryNumber+1);
}).start();
primaryNumber+=2;
}
return Duration.between(start, Instant.now()).toMillis();
}
public static long findPrime() throws IOException {
Instant instant = Instant.now();
int primaryNumber = 3;
while (primaryNumber <= 100000) {
multiplicationHelper(primaryNumber);
primaryNumber++;
}
return Duration.between(instant, Instant.now()).toMillis();
}
public static void multiplicationHelper(int primaryNumber){
int j = 2;
boolean isPrime = true;
while (j <= primaryNumber/2) {
if (primaryNumber % j == 0) {
isPrime = false;
break;
}
j++;
}
if (isPrime) {
// System.out.println("PRIME :: " + primaryNumber);
}
}
}
这是代码,代码的输出为:
Without Thread497 ms
With thread : 22592 ms
请您详细说明为什么以及如何提高多线程性能?我是多线程编程的新手,所以我在做错什么吗?
“查找素数”是compute-bound操作。它自然会使用100%的CPU利用率,因为它不需要执行I / O。
“多线程”的两个目的是:(a)利用多个CPU内核,以及(b)使计算与I / O重叠。 (并且更轻松地发出并行I / O操作。)
在适当的情况下,多线程处理可以节省时间,在错误的情况下,或会花费更多的时间。
您考虑不周的设计似乎启动了20,000个线程!