i'm new to multithreading. So here is the problem I'm working on: Store the last four digits of your student ID in two separate classes. For example, if your ID is SE123456789 then store 67 in first Thread1 Class and 89 in Thread2 Class that will be passed to Factorial class later.
Thread1 class will pass 67 to the Factorial class and printfactorial() will print factorial of all the numbers from 1 to 67.
Thread2 class will pass 89to the Factorial class and printfactorial() will print factorial of all the numbers from 1 to 89.
You should use thread.sleep(10) after each calculation inside the loop.
As you know that you cannot store and print factorial of large numbers in simple integer or long type variables, so you are required to use BigInteger to store and print very long numbers.
printfactorial() method must be synchronized so that the results of Thread1 are printed first then the result of Thread2 is calculated and printed.
and here's what I have done so far.
I have four different classes
Main
Factorial
Thread1
Thread2
Thread1 and Thread2 both extend Thread class. here's the code I wrote so far:
Main
public class Main {
public static void main(String args[]){
Factorial factorial = new Factorial();
Thread1 t1 = new Thread1(factorial);
Thread1 t2 = new Thread1(factorial);
t1.start();
t2.start();
}
}
Factorial Class
import java.math.BigInteger;
public class Factorial {
public void printFactorial(int number){
BigInteger bigInteger = new BigInteger("1");
try{
for(int i=1; i<=number; i++){
bigInteger = bigInteger.multiply(BigInteger.valueOf(i));
Thread.sleep(10);
System.out.println(bigInteger);
}
}catch(InterruptedException ex){
System.out.println("the interruption has occurred in the thread");
}
}
}
Thread1
package com.mycompany.factorial;
public class Thread1 extends Thread {
Factorial factorial;
Thread1(Factorial fact){
factorial = fact;
}
@Override
public void start(){
synchronized(factorial){
try{
/*my ID is: SE170400080
so the second last two digits are 00.
**/
factorial.printFactorial(00); //here's the problem
}catch(Exception e){
System.out.println("the interruption has occurred in the thread");
}
}
}
}
Thread2
package com.mycompany.factorial;
public class Thread2 extends Thread {
Factorial factorial;
Thread2(Factorial fact){
factorial = fact;
}
@Override
public void start(){
synchronized(factorial){
try{
factorial.printFactorial(80);
}catch(Exception e){
System.out.println("the interruption has occurred in the thread");
}
}
}
}
after running the main it builds successfully but does not show the required output.
help would be really appreciated, I tried best to keep it on point.
1:
