2

The thread is interrupted at 5 sec. In isPrime function, if the if(num % 2 == 0) is commented, the code prints to 85427 whereas with the if it prints only till 83761. Kindly help in understanding this absurd behavior in multithreading.

public void run(){

    long number = 1l;

    while(true){
        if(isPrime(number)){
            System.out.println("Number is prime number : " + number);
        }
        if(isInterrupted()){
            System.out.println("The Prime generator has been interrupted");
            return;
        }
        number++;
    }
}

public boolean isPrime(long num){
    if(num <= 2){
        return true;
    }
    else{
        if(num % 2 == 0){
            return false;
        }
        else{
        for(long i = 3; i < num ; i++ ){
            if((num % i) ==  0){
                return false;
            }
        }
    }
    }

    return true;
}
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
Atul
  • 45
  • 1
  • 2
  • 7
  • 2
    Well, from the top, i would say that if you remove the IF condition, your CPU has to do lesser computation and hence it calculates more primes in that 5 sec period – Pratik May 10 '15 at 09:08
  • It seems strange that the not-if version is faster when running for 5000ms. I could expect it with smaller values but, after a certain number the if version should be considerably faster, as even numbers will be processed faster. I guess it is a bad-measurement issue rather than a performance issue. – Kostas Kryptos May 10 '15 at 09:41
  • How often did you try your tests? – duffy356 May 10 '15 at 09:43

3 Answers3

1

Well, from the top of my head, I would say that if you remove the IF condition, your CPU has to do lesser computation and hence it calculates more primes in that 5 sec period.

Maroun
  • 94,125
  • 30
  • 188
  • 241
Pratik
  • 1,122
  • 8
  • 26
0

When removing the condition check you are making the thread execution faster because of that you are reaching a higher value.

Hussein Zawawi
  • 2,907
  • 2
  • 26
  • 44
0

The difference in computation time is 2%. That is probably below common standard error.

Did you do proper microbenchmarking, to find these times?

BTW, your code could quite see some optimization.

Community
  • 1
  • 1
Fox
  • 2,348
  • 19
  • 19