Commit 1b245fae authored by ubay.alshamali's avatar ubay.alshamali

Initial commit

parents
import java.util.ArrayList;
import java.util.List;
public class PrimeFinder
{
public static void main(String[] args)
{
long startTime = System.nanoTime();
int threadsNum = 5;
int start = 1;
int end = 100000;
int batch = (end-start+1)/(threadsNum-1);
Thread[] threads = new Thread[threadsNum];
RunnablePrimeFinder[] runnables = new RunnablePrimeFinder[threadsNum-1];
for(int i = 0; i<threadsNum-1; i++)
{
runnables[i] = new RunnablePrimeFinder((i)*batch +1,batch * (i+1));
threads[i] = new Thread(runnables[i]);
threads[i].start();
}
threads[threadsNum-1] = new Thread(()->
{
for(int i = 0; i<threadsNum-1;i++)
{
try
{
threads[i].join();
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
}
for(int i = 0;i<threadsNum-1;i++)
{
System.out.println("Prime numbers in thread " + (i + 1) + ": " + runnables[i].getPrimeNumbers());
}
});
threads[threadsNum-1].start();
long endTime = System.nanoTime();
long executionTime = endTime - startTime;
System.out.println("Execution time: " + executionTime + " nanoseconds");
System.out.println("Execution time: " + (executionTime / 1_000_000) + " milliseconds");
}
}
class RunnablePrimeFinder implements Runnable
{
private int start;
private int end;
private List<Integer> primeNumbers;
public RunnablePrimeFinder(int s, int e)
{
start = s;
end = e;
primeNumbers = new ArrayList<Integer>();
}
@Override
public void run()
{
for(int i = start; i<=end; i++)
{
if(isPrime(i))
{
primeNumbers.add(i);
}
}
}
private boolean isPrime(int n)
{
if (n <= 1) {
return false;
}
if (n <= 3) {
return true;
}
if (n % 2 == 0 || n % 3 == 0) {
return false;
}
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
}
public List<Integer> getPrimeNumbers()
{
return primeNumbers;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment