繁体   English   中英

如何将数组拆分为多个线程Java

[英]How to split an array into multiple threads Java

所以我有一个MaxThread类,run()方法将传递的向量的最大值存储到maxValue类属性中。 我想将10个整数的初始数组分成4个子数组,每个子数组具有不同的线程。 在我从4个子数组中的每一个找到4个最大值之后,我想创建一个新的MaxThread并从中显示最大值。 这段代码有效,但是我想不出更好的方法,因为我确定自己做的很愚蠢(我对此并不陌生)。

public class Main{

    public static void main(String[] args) {
        int step = 3;
        Integer[] vector = new Integer[10];
        readFromFile(vector);
        int i = 0;
        ArrayList<MaxThread> threads = new ArrayList<>();
        MaxThread t1 = null;
        MaxThread t2 = null;
        MaxThread t3 = null;
        MaxThread t4 = null;

            t1 = new MaxThread(vector, 0, 3);
            threads.add(t1);
            t1.start();

            t2 = new MaxThread(vector, 3, 6);
            threads.add(t2);
            t2.start();

            t3 = new MaxThread(vector, 6, 9);
            threads.add(t3);
            t3.start();

            t4 = new MaxThread(vector, 9, 10);
            threads.add(t4);
            t4.start();


        for (MaxThread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        Integer[] last = new Integer[4];
        last[0]=t1.getMaxVal();
        last[1]=t2.getMaxVal();
        last[2]=t3.getMaxVal();
        last[3]=t4.getMaxVal();

        MaxThread lastThread = new MaxThread(last, 0, last.length);
        lastThread.start();
        try {
            lastThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Valoarea maxima:" +lastThread.getMaxVal());
    }

这对于并行流是一个很好的情况。 通常,只有拥有至少数万个元素的多线程才值得。 在这些情况下,拥有原始数组也是值得的。

public static void main(String[] args) {
    int[] vector = // ...
    int max = Arrays.stream(vector).parallel().max().getAsInt();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM