Thread coordination


কেন থ্রেড কোঅরডিনেশন দরকার

  • থ্রেড স্বাধীনভাবে চলে 
  • থ্রেড এর অর্ডার আমাদের হাতে থাকে না


থ্রেড কোঅরডিনেশন করার জন্য thread.join() মেথড ব্যাবহার করা যায়।  থ্রেড টাইম মত কাজ শেষ করলে এবং join() দেয়া থাকলে কাজ শেষ কন্ট্রোল মেইন থ্রেডের কাছে ফিরে আসে।  thread .join() এর ভিতর টাইমআউট দেয়া যায়, এই টাইম এর মধ্যে কাজ শেষ না হলে কন্ট্রোল মেইন থ্রেড এর কাছে চলে আসবে। 

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

public class ThreadCoordination {
    public static void main(String[] args) {
        List<Long> inputs = List.of(10000000000L, 200L, 3333L, 40000L, 5L, 600L, 7L, 8L, 9L, 10L);

       List<FactorialThread> threads = new ArrayList<>();
       for (Long input : inputs) {
           threads.add(new FactorialThread(input));
       }

       for (FactorialThread thread : threads) {
           thread.start();
       }

       for(Thread thread: threads) {
           try {
               thread.join(2000);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }

       for (int i=0; i < inputs.size(); i++) {
           FactorialThread factorialThread = threads.get(i);
           if(factorialThread.isFinished()) {
               System.out.println("Factorial of " + inputs.get(i) + " is " + factorialThread.getResult());
           } else {
               System.out.println("The calculation for " + inputs.get(i) + " is still in progress");
           }
       }



    }

    public static class FactorialThread extends Thread {
        private long inputNumber;
        private BigInteger  result = BigInteger.ZERO;
        private boolean finished = false;

        public FactorialThread(long inputNumber) {
            this.inputNumber = inputNumber;
        }

        @Override
        public void run() {
            this.result = factorial(inputNumber);
            finished = true;
        }

        public BigInteger factorial(long n) {
            BigInteger result = BigInteger.ONE;
            for (long i = 1; i <= n; i++) {
                result = result.multiply(BigInteger.valueOf(i));
            }
            return result;
        }

        public boolean isFinished() {
            return finished;
        }

        public BigInteger getResult() {
            return result;
        }
    }
}