0

this is my code in which i need generate a random number and store in numb variable and pass it to another thread to get the factorial. Need output like this:

Number : 2 Factorial of 2 : 2 Number : 5 Factorial of 5 : 120

run this for 5 times

public class assignment1 {

    public static void main(String args[])
    {
        static int numb=0;

        for(int i=0;i<5;i++)
        {
        Thread t1 = new Thread() 
                {

            public void run()
            {
                numb = (int) Math.random() * 10;
                System.out.println("Number : "+numb);
            }
                };

        Thread t2 = new Thread()
                {
            int fact = 1;
            public void run()
            {
                for(int x=1;x<=numb;x++)
                {
                    fact=fact*x;
                }
                System.out.println("Factorial of "+numb+" is "+fact);
            }
                };
                t1.start();
                t2.start();

        }   
    }
Krishna Kr
  • 21
  • 1
  • 1
  • 7
  • Ok, but what is the problem? Does the code compile? Any errors? The output is incorrect? What is the actual vs expected output? – Amongalen Mar 26 '20 at 14:34
  • See [How can I pass a parameter to a Java Thread?](https://stackoverflow.com/questions/877096/how-can-i-pass-a-parameter-to-a-java-thread) – Idle_Mind Mar 26 '20 at 14:48
  • why would you create threads in a loop – Abhinav Chauhan Mar 26 '20 at 14:55
  • `(int) Math.random()` is always zero, see the duplicate for the right way to generate random integers in a range – Joni Mar 26 '20 at 15:23
  • @Joni thats why I have multiplied it with 10 , then it will give random number my question is that how tp run multiple thread and pass that random number to factorial thread – Krishna Kr Mar 27 '20 at 06:51
  • Zero multiplied by 10 is still zero. see the duplicate for the right way to generate random integers in a range – Joni Mar 27 '20 at 11:01
  • @Joni ok that I will fix please update regarding the thread. – Krishna Kr Mar 27 '20 at 13:38
  • I see, I mistook that for the cause of the problem. Were you given any instructions for how the data should be or shouldn't be passed from one thread to the other - can you use classes from the standard library? – Joni Mar 27 '20 at 14:20

0 Answers0