javamultithreadingexecutorservicecallableexecutors

Finding the factorial using callable interface in java


package projsamples;

import java.util.Collection;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class FactorialUsingThreads {

    public static void main(String[] args)  throws InterruptedException,ExecutionException{

        Scanner reader = new Scanner(System.in);
        int number = reader.nextInt();
        ExecutorService es = Executors.newSingleThreadExecutor();
        Future<Integer> result=es.submit(new FactorialCalc(number));
        System.out.println("result value after calc is: "+ result);
        int finalResult =(int)result.get();
        System.out.println("The result of the factorial calculation for the"+number+"is: "+finalResult);
    }

    }

    class FactorialCalc implements Callable<Integer>{

    private int number;

    public FactorialCalc(int number) {
        super();
        this.number = number;
    }

    @Override
    public Integer call() throws Exception {
        // TODO Auto-generated method stub
        return factorial(number);
    }

    private Integer factorial(int number2) throws InterruptedException  {
        // TODO Auto-generated method stub
        int number = number2;
        int result = 1;
        while(number2 !=0){

            result = number*result;
            number=number-1;
            Thread.sleep(100);

        }
        System.out.println("result"+result);
        return result;

    }
}

In the above code what I am trying to do is, I want to find the factorial number for any number entered by user. The result returned is the object when I try to typecast the integer object and the get the value is not happening. I know this could be a very basic thing which I am not able to do.any small heads up on this would be helpful.

Thanks a lot in advance for all the kind people who can help.


Solution

  • This has to do with multithreading. You just need number2 in factorial method, and remember decrement it.

    private Integer factorial(int number2) throws InterruptedException  {    
        int result = 1;
        while(number2 != 0){    
            result = number2 * result;
            number2 = number2 - 1;
            Thread.sleep(100);    
        }
        System.out.println("result"+result);
        return result;    
    }