在Java中创建三个线程来计算三个不同的项目

我正在尝试编写我的解决方案来解决
Java中的多线程问题:

Create three separate threads that will calculate the average, minimum
and maximum of a series of numbers that is passed to the program. The
values will be stored globally in the program. The three threads will
return the three values respectively to the main program where it will
be output to the user.

我是Java的新手,所以我对这个程序的方法有一个基本的问题:如何创建三个独立的线程来执行三个不同的功能?在阅读多线程时,我遇到了几个例子,其中创建了三个(或更多)线程,每个线程执行一个函数:倒计数循环.因此,只需要对public void run()进行一次调用,就可以非常轻松地创建一个实现Runnable的类的三个实例,例如:

// 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.");
       }
}

我不知道如何创建执行单独功能的线程:计算double,min和max.到目前为止,我已经创建了一个计算平均值的线程并将其返回给主程序.这是我的代码[到现在为止]:

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);
    }

}

我现在有两个问题:

>有人可以给我创建两个计算最小值和最大值的线程的方法吗?
>我的代码(到目前为止)是否存在我应该注意的OOP缺陷?

最佳答案 你可以做的是创建另外两个计算min和max的类,创建每个类obj1和obj2的对象.由于构造函数为您启动线程,因此您现在应该有3个异步运行的线程.

在该try块中调用obj1.t.join()和obj2.t.join().所以看起来应该是这样的:

   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();

然后用这些数字做你想做的事.

至于一些一般性注释,首先我不会在runnable类中有一个线程对象作为属性,也没有构造函数中的start()方法.相反,在主类中,我鼓励您使用每个可运行类的实例创建三个线程对象,然后在每个对象上调用start()方法.而且,而不是三个runnable
所有类都与Q7Main中的相同静态数组进行交互,我会改为更新它们
构造函数接受数组作为构造函数中的参数,然后在调用其run方法时让它们中的每一个与唯一的数组对象进行交互.否则,您遇到的问题是,当一个线程更改数组中某些内容的值时,您会得到意外的结果.

当然,在这种情况下,你的课程都没有这样做,但要记住它.

例如

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();
点赞