I'm starting to learn parallel programming, and I'm wanting to compare a single threaded program to a multithreaded one.
What I thought was to make a very simple algorithm that, within a period of 1 minute, calculate the largest number of possible prime numbers, and show me the last calculated prime number and its position in the prime numbers, for example , let's say it was number 23, would appear the number 23 and its position, in case 9, since it is the 9th prime number.Without using parallelism, the number found was 774107, at position 62039. However, when using parallelism, I got the number 1083757, at position 84444 (wrong position, the right would be 84547), I believe it was a good mistake basic, but as I still do not understand much of parallelism, I could not solve it.
Below is the code of the two classes I created, the first one is the Calculate class that only serves to define the instances and implement the run method. The second is Main class.
Calculate:
import java.util.Collection;
public class Calcula extends Thread {
private int x;
private int quantidade = 0;
private int ultimo = 0;
private long tempoInicial;
public Calcula(int x, long tempoInicial) {
this.x = x;
this.tempoInicial = tempoInicial;
}
public int getQuantidade (){
return quantidade;
}
public int getUltimo (){
return ultimo;
}
@Override
public void run() {
long tempoMaximo=tempoInicial;
while (tempoMaximo < tempoInicial+60000){
tempoMaximo = System.currentTimeMillis();
for(int z=2; z<x/2; z++){
if (x%z==0) break;
else if(z==(x/2)-1){
quantidade++;
ultimo=x;
}
}
x=x+8;
}
}
}
Main:
import java.util.ArrayList;
import java.util.Collection;
public class Principal{
public static void main(String[] args){
long tempoInicial = System.currentTimeMillis();
Calcula t1 = new Calcula (5, tempoInicial);
Calcula t2 = new Calcula (7, tempoInicial);
Calcula t3 = new Calcula (9, tempoInicial);
Calcula t4 = new Calcula (11, tempoInicial);
t1.start();
t2.start();
t3.start();
t4.start();
try{
t1.join();
t2.join();
t3.join();
t4.join();
} catch (InterruptedException ex){
ex.printStackTrace();
}
int ultimo = t1.getUltimo();
if (ultimo < t2.getUltimo()) ultimo = t2.getUltimo();
if (ultimo < t3.getUltimo()) ultimo = t3.getUltimo();
if (ultimo < t4.getUltimo()) ultimo = t4.getUltimo();
System.out.println("Último primo encontrado: " + ultimo);
System.out.println("Quantidade de primos encontrados: " + (t1.getQuantidade() + t2.getQuantidade() + t3.getQuantidade() + t4.getQuantidade()));
}
}
The logic I followed was to start each thread with a different value and implement it every 8, so that neither of them computes repeated values. In the end, I get the getQuality of each and somo, and I see the largest getUltimo to get the highest value. I think the error is because some thread is calculating a bit faster, so the amount goes wrong.