Creating three threads in Java to compute three different elements

I am trying to write a solution to the multithreading problem in Java:

Create three separate threads that will calculate the average, minimum and maximum of the number of numbers passed to the program. the values โ€‹โ€‹will be stored globally in the program. Three threads will return three values โ€‹โ€‹respectively to the main program, where it will be displayed to the user.

I'm new to Java, so I have one basic question about approaching this program: How do I create three separate threads that will perform three different functions ? Reading multithreading, I encountered a few examples in which it was created three (or more) of the flow, each of which would perform a single function: counting down a loop

. This way only one call is required public void run()

and it is very easy to create three instances of the class that implements Runnable to do this, e.g .:

// Create multiple threads.
       class NewThread implements Runnable {
         String name; // name of thread
         Thread t;
         NewThread(String threadname) {
           name = threadname;
           t = new Thread(this, name);
           System.out.println("New thread: " + t);
           t.start(); // Start the thread
}
         // This is the entry point for thread.
         public void run() {
          try {
             for(int i = 5; i > 0; i--) {
               System.out.println(name + ": " + i);
               Thread.sleep(1000);
             }
           } catch (InterruptedException e) {
             System.out.println(name + "Interrupted");
}
           System.out.println(name + " exiting.");
         }
}

  class MultiThreadDemo {
       public static void main(String args[]) {
         new NewThread("One"); // start threads
         new NewThread("Two");
         new NewThread("Three");
         try {
           // wait for other threads to end
           Thread.sleep(10000);
         } catch (InterruptedException e) {
           System.out.println("Main thread Interrupted");
}
         System.out.println("Main thread exiting.");
       }
}

      

I'm not sure how to create threads that do separate functions: calculate double, min and max. So far, I've created one thread that calculates the average and returns it to the main program. This is my code [so far]:

package assignment2;
class Q2Thread implements Runnable {


    String name;
    Thread t;
    private int average;
    int sum=0;

    Q2Thread(String name)
    {
        this.name=name;
        t=new Thread(this, name);
        //System.out.println("This thr");
        t.start();
    }

    public void run()
    {
        try
        {
            for(int i=0;i<Q7Main.arr.length;i++)
                sum+=Q7Main.arr[i];

            average=sum/Q7Main.arr.length;



        }
        //catch(InterruptedException e)
        finally
        {
            System.out.println("Calcuated average.");
        }

    System.out.println("Child Thread exiting.");
    }

    public int getAverage() 
    {
        return average;
    }

}

package assignment2;
import java.util.*;
public class Q7Main {

     public static int[] arr=new int[5];

    static Scanner in=new Scanner(System.in);
    private static int finalAverage;


    public static void main(String[] args) {
        // TODO Auto-generated method stub


        System.out.println("Please enter the numbers: " );
        for(int i=0;i<arr.length; i++)
            arr[i]=in.nextInt();
        System.out.println("You entered the numbers: ");
        for(int x: arr)
            {
            System.out.print(x+ " ");
            }
        System.out.println();

        Q2Thread obj=new Q2Thread("Average");

        try
        {
            obj.t.join();
        }
        catch(InterruptedException e)
        {
            System.out.println("Interrupted.");
        }

        finalAverage=obj.getAverage();
        System.out.println("The average of the numbers is: "+ finalAverage);
    }

}

      

I have two questions:

  • Can anyone give me an approach to create two more threads that will calculate min and max?
  • Are there any OOP flaws in my code (so far) that I should be aware of?
+3


source to share


2 answers


What you can do is create two other classes that compute min and max, create an object for each obj1

and obj2

. Since the constructor starts the thread for you, you should now have 3 threads running asynchronously.

Call obj1.t.join()

and obj2.t.join()

inside this try block. So it should look like this:

   try{
        obj.t.join();
        obj1.t.join();
        obj2.t.join();
   }
   catch(InterruptedException e)
   {
       System.out.println("Interrupted.");
   } 
   int average = obj.getAverage();
   int max = obj1.getMax();
   int min = obj2.getMin();

      

And then do whatever you want with those numbers.



As with some general comments, firstly, I would not have the stream object as an attribute inside the runnable class, and also no method start()

inside the constructor. Instead, in the main class, I would suggest that you create three thread objects with an instance of each runnable class, and then call a method start()

on each of them. Also, instead of the three managed classes that interact with the same static array found in Q7Main

, I would instead update their constructors to accept the array as a parameter in the constructor, and then each one interacts with a unique array object when the method is called launch them. Otherwise, there is a problem, when one thread changes the value of something in the array, you get unexpected results.

Of course, in this case, none of your classes do this, but it needs to be remembered.

for example

Q2Thread obj =new Q2Thread("Average", arr);
Q2MaxThread obj1 = new Q2MaxThread("Maximum", arr);
Q2MinThread obj2 = new Q2MinThread("Minimum", arr);
Thread avThread = new Thread(obj);
Thread maxThread = new Thread(obj1);
Thread minThread= new Thread(obj2);

avThread.start();
maxThread.start();
minThread.start();

   try{
        avThread.join();
        maxThread.join();
        minThread.join();
   }
   catch(InterruptedException e)
   {
       System.out.println("Interrupted.");
   } 
   int average = obj.getAverage();
   int max = obj1.getMax();
   int min = obj2.getMin();

      

0


source


In addition to @ ElvenAshwin's answer, you should probably accept three classes as a private inner class ... good practice as you create more stuff that you don't pollute the public api. As an alternative and good exercise, think about it with lambdas in java 8. Its just a function where you don't need a class.



0


source







All Articles