I have written a simple program to find the factorial of the numbers. I am using the join()
method of Thread
class for better thread coordination ( and to avoid the race condition). I am adding the code below.
public static void main(String[] args) throws InterruptedException {
List<Long> listOfNumbers = new ArrayList<>(Arrays.asList(100031489L, 4309L, 0L, 199L, 333L, 23L));
List<FactorialCalculations> threadList = new ArrayList<>();
for (Long number : listOfNumbers) {
threadList.add(new FactorialCalculations(number));
}
for (Thread thread : threadList) {
thread.start();
}
for (Thread thread : threadList) {
thread.join(3000);
}
// Thread.sleep(1000);
for (int i = 0; i < listOfNumbers.size(); i++) {
FactorialCalculations factorialCalculationsThread = threadList.get(i);
if (factorialCalculationsThread.isStatus()) {
System.out.println("Factorial of number " + listOfNumbers.get(i) + " : " + factorialCalculationsThread.getResult());
} else {
System.out.println("still processing for " + listOfNumbers.get(i));
}
}
}
Whenever I am inputting a big value (100031489L), the main thread is printing the outputs of the numbers except for this one, and the program isn't getting terminated. I have used two approaches - Daemon threads thread.setDaemon(true)
and thread.interrupt()
with Thread.currentThread().isInterrupted()
(if true print the results) to terminate the program. Both approaches have worked but I would like to know which is a more appropriate approach to use in my scenario.
Thanks in advance!