Home > other >  Using multi-threaded calculation from 1 to 100000 the number of prime Numbers within 4 CPU can use e
Using multi-threaded calculation from 1 to 100000 the number of prime Numbers within 4 CPU can use e

Time:12-04




As title, please answer, it is best to say the specific ideas and paste the code implementation

CodePudding user response:


Such as finding the latest prime number is 37
The 100000 is divided into four segments
(0250, 00], (25000500, 00], (50000750, 00], (75000100, 000]
Four section, find the first 37 multiples,
0/37 (+ 1) * 37=37, 25000/37 (+ 1) *=25012, 37 (50000/37 + 1) *=50024, 37 (75000/37 + 1) * 37=75036
Four threads respectively with the starting number, since by 37 step length, play tag,



CodePudding user response:


I first bits

CodePudding user response:


Forkjoin?

CodePudding user response:

Package com. Buba. Threadpool;

import java.util.ArrayList;
import java.util.List;
Import the Java. Util. Concurrent. *;

/* *
* need to modify the
*/
Public class T07_ParallelComputing {
Public static void main (String [] args) throws ExecutionException, InterruptedException {
long start=System.currentTimeMillis();
List List=getPrime (1, 200000);
Long end=System. CurrentTimeMillis ();
System. The out. Println (" common computing time: "+ (end - start));
System. The out. Println ("=================================");
Final int cpuCoreNum=4;
The ExecutorService service=Executors. NewFixedThreadPool (cpuCoreNum);

MyTask task1=new MyTask (1, 80000);
MyTask task2=new MyTask (80001, 130000);
MyTask task3=new MyTask (130001, 170000);
MyTask task4=new MyTask (170001, 200000);
Future F1=service. Submit (task1);
Future F2=service. Submit (task2);
Future F3=service. Submit (task3);
Future F4=service. Submit (task4);
Start=System. CurrentTimeMillis ();
F1. The get ();
F2. The get ();
F3. The get ();
F4. The get ();
Service. The shutdown ();
End=System. CurrentTimeMillis ();
System. The out. Println (" parallel computing time: "+ (end - start));
/* *
* D: \ JAVA \ JDK \ bin \ JAVA exe
* general computation time consuming: 1585
*=================================
* parallel computing time: 531
*/
}

Static class MyTask implements Callable {
Int startPos endPos;

Public MyTask (int startPos, int endPos) {
Enclosing startPos=startPos;
Enclosing endPos=endPos;
}

@ Override
Public List Call () throws the Exception {
List List=getPrime (startPos endPos);
Return the list;
}

}
//whether a number is prime
The static Boolean isPrime (int num) {
For (int I=2; I & lt; Num/2; I++) {
If (num % I==0) return false.
}
return true;
}

The static List GetPrime (int start, int the end) {
List Results=new ArrayList<> (a);
For (int I=start; I & lt; end; I++) {
If (isPrime (I)) results. The add (I);
}
Return the results.
}

}
  • Related