dimanche 10 mai 2015

Why does in the following Threading code, the for loop iterates more prime number than if

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;
}

Aucun commentaire:

Enregistrer un commentaire