Aspirant
Aspirant

Reputation: 11

java Prime Number Problem in Multiple Thread

My code looks like this:

public class Demo {

   public static void main(String[] args) throws InterruptedException {
      primeGen prime = new primeGen(10, 50);

      Thread th1 = new Thread(prime);
      th1.setName("Thread1");

      Thread   th2 = new Thread(prime);
      th2.setName("Thread2");

      th1.start();
      th2.start();
   }
}

class primeGen implements Runnable {
   private int N1,N2;
   private volatile int i;

   public primeGen(int n1, int n2) {
        this.N1 = n1;
        this.N2 = n2;
        i = N1;
   }

   private boolean isPrime(int N) {
      for(int j = 2; j <= N / 2; j++) {
         if(0 == N % j) return false;
      }
      return true;
   }

   private void primeRange(int N1 , int N2){

      Thread th = Thread.currentThread();

      for(; i <= N2; i++) {

      if(isPrime(i))
        System.out.print(th.getName() + " " + i + " is prime \n");
      }
   }

   @Override
   public void run() {
      primeRange(N1 , N2);
   }
}

Current output of the console:

Why are some prime numbers repeated by multiple threads and how can i prevent this?

Upvotes: 0

Views: 116

Answers (1)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79115

Synchronise isPrime and primeRange to avoid more than one threads accessing them at the same time. Learn more from here.

public class Demo {

    public static void main(String[] args) throws InterruptedException {
        primeGen prime = new primeGen(10, 50);
        Thread th1 = new Thread(prime);
        th1.setName("Thread1");
        Thread th2 = new Thread(prime);
        th2.setName("Thread2");
        th1.start();
        th2.start();
    }
}

class primeGen implements Runnable {
    private int N1, N2;
    private volatile int i;

    public primeGen(int n1, int n2) {
        this.N1 = n1;
        this.N2 = n2;
        i = N1;
    }

    private synchronized boolean isPrime(int N) {
        for (int j = 2; j <= N / 2; j++) {
            if (0 == N % j) {
                return false;
            }
        }
        return true;
    }

    private synchronized void primeRange(int N1, int N2) {
        Thread th = Thread.currentThread();
        for (; i <= N2; i++) {
            if (isPrime(i)) {
                System.out.print(th.getName() + " " + i + " is prime \n");
            }
        }
    }

    @Override
    public void run() {
        primeRange(N1, N2);
    }
}

Upvotes: 1

Related Questions