This program runs 4 threads and searches for prime numbers from 1 to 100. Sometimes 2 threads are simultaneously attacking and numbers are repeated. I tried to synchronize the thread but I do not know how to do it well. Can I you can help? Sorry for my bad English
import java.util.ArrayList;
public class EjemploThread1 extends Thread{
static int numero=1;
static ArrayList<Integer> primos = new ArrayList<Integer>() ;
public synchronized void run() {
//try {
while (numero < 100){
numero++;
if (!primos.contains(numero) && esPrimo(numero))
{
primos.add(numero);
}
notifyAll();
//yield();
try {
sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//MAIN
public static void main(String[] args) throws InterruptedException {
EjemploThread1 hilos = null;
int n_hilos=4;
//Crear los 4 Hilos
for (int i=0;i<=n_hilos;i++) {
hilos = new EjemploThread1();
hilos.start();
}
for (int i=0;i<=n_hilos;i++) {
hilos.join();
}
//cuando finalizen los hilos(join) continuara y mostrara el vector:
System.out.println("\nVECTOR NUMEROS PRIMOS: ");
for(int i=0; i < primos.size(); i++)
{
System.out.print(primos.get(i) + " ");
}
}
//FUNCION SABER SI ES PRIMO
public static boolean esPrimo(int numero)
{
for(int i=2; i<numero; i++)
{
if(numero % i == 0) return false; //no es primo
}
return true; //es primo
}
}