Aakashシャルマ:
私は、この問題の解決策を見つけることを試みたが、StackOverflowの上でそれを見つけることができませんでしたか?
私はなぜそれが反対のことを行っている必要があります私のmultithreadin作業遅いのでInfactはであることを知ってほしいです。
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
マルチスレッドのパフォーマンスを向上させるようにし、どのように、なぜあなたは私を詳しく説明することができますしてください?私は、マルチスレッドプログラミングに新しいですので、私はこれで何かが間違っているのでしょうか?
Kid101:
に下記にあなたの関数を変更します
public static long findPrimeWithThreads() {
Instant start = Instant.now();
int primaryNumber = 3;
ExecutorService pool = Executors.newFixedThreadPool(4); // considering you've 4 CPU
while (primaryNumber <= 100000) {
int finalPrimaryNumber = primaryNumber;
pool.submit(()->multiplicationHelper(finalPrimaryNumber));
primaryNumber ++;
}
pool.shutdown(); // stop your threads
return Duration.between(start, Instant.now()).toMillis();
}