hyung jun cho
hyung jun cho

Reputation: 13

How can i get multi thread parallel calculator (factorial sum)

I will input some number to calculates sum of Factorial series, like if i put 5, output will be 1!+2!+3!+4!+5!, but calculating processing could be heavy so i want to use multiple treads that calculates each factorial.. means thread1 cals 1!, thread2 cals 2!... i used arrays of threads but can't sync them in propel results. and can't find the way to sum these results.

i wrote codes...

public class Calthread extends Thread{
    private int num=1;
    public Calthread(int num) {
        this.num = num;
    }

    public void run() {
        int dft = 1;
        for(int i=1; i<=num; i++) {
            dft = dft*i;
        }
        System.out.println(num + "! result :" + dft);
    }

}

this is for 1 thread

for main class

public class calculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("input number>>");
        int k = scanner.nextInt();  //input 'k'

        int sum = 0;

        Calthread[] cal = new Calthread[k]; // make threads number of 'k'
        for(int i = 0; i<k; i++) {
            cal[i] = new Calthread(i+1);
            cal[i].start();
        }
    }

}

how can I Sync them and print the sum of all?

Upvotes: 1

Views: 952

Answers (1)

Roman Danilov
Roman Danilov

Reputation: 371

To return value from thread you should use Callable instead of Runnable:

public class Calthread implements Callable<Integer> {

    private int num = 1;

    public Calthread(int num) {
        this.num = num;
    }

    @Override
    public Integer call() {
        int dft = 1;
        for (int i = 1; i <= num; i++) {
            dft = dft * i;
        }
        return dft;
    }
}

And in the main class:

public class Calculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("input number>>");
        int k = scanner.nextInt();  //input 'k'

        int sum = 0;
        // Make threads number of 'k'. Here we use List instead of array because there is such contract in ExecutorService
        List<Calthread> cal = new ArrayList<>(k);
        // Create thread pool with fixed number of threads
        ExecutorService service = Executors.newFixedThreadPool(k);
        // Add all Callable task in one collection
        for (int i = 0; i < k; i++) {
            cal.add(new Calthread(i+1));
        }
        try {
            // Invoke all Callable task and get List with results
            List<Future<Integer>> results = service.invokeAll(cal);
            // Future::get is blocking method. It waits result.
            for (Future<Integer> result : results) {
                sum += result.get();
            }
        } catch (InterruptedException | ExecutionException e) {
            System.out.println("Something went wrong");
            e.printStackTrace();
        }

        System.out.println("Result: " + sum);
        // We need to shutdown our service
        service.shutdown();
    }
}

Upvotes: 1

Related Questions