简体   繁体   English

java - 线程(从数组中返回一个元素)

[英]java - threads (returning an element from an array)

can someone tell me why the thread returns 0 after running this code, and not the max value from the array (the array must be as large as possible), how can I fix it?有人可以告诉我为什么线程在运行此代码后返回 0,而不是数组中的最大值(数组必须尽可能大),我该如何解决?

import java.util.Arrays;

public class MyThread extends Thread {

    int[] arr = new int[1000000];

    public static int max(int[] numbers) {
        int maxValue = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > maxValue) {
                maxValue = numbers[i];
            }
        }
        return maxValue;
    }

    public static int min(int[] numbers) {
        int minValue = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] < minValue) {
                minValue = numbers[i];
            }
        }
        return minValue;
    }

    @Override
    public void run() {
        int maxArr = max(Arrays.stream(arr).toArray());
        System.out.println(maxArr);
    }

    public static void main(String[] args) {
        MyThread Thread1 = new MyThread();
        Thread1.start();
    }
}

Your array cells are not initialized, so all value are zero.您的数组单元未初始化,因此所有值都为零。 Write 666 to arr[0] and have a nice day.将 666 写入 arr[0] 并祝您有美好的一天。

Your array你的阵列

int[] arr = new int[1000000];

is array that filled with zeros , coz the default value of int is 0 .用零填充的数组,因为 int 的默认值为0

You should assign some values to array elements otherwise default values 0 are used.您应该为数组元素分配一些值,否则使用默认值 0。

You are passing an array arr which has only zero for all the index which means you need to initialise the array with values like below.您正在传递一个数组arr ,它的所有索引都只有零,这意味着您需要使用如下值初始化数组。

import java.util.Arrays;

class MyThread extends Thread {

int[] arr = new int[1000000];

public static int max(int[] numbers) {
    int maxValue = numbers[0];
    for (int i = 1; i < numbers.length; i++) {
        if (numbers[i] > maxValue) {
            maxValue = numbers[i];
        }
    }
    return maxValue;
}

public static int min(int[] numbers) {
    int minValue = numbers[0];
    for (int i = 1; i < numbers.length; i++) {
        if (numbers[i] < minValue) {
            minValue = numbers[i];
        }
    }
    return minValue;
}

@Override
public void run() {
    //initialise array with values
    for (int i = 0; i < arr.length; i++) {
        arr[i] = i;
    }
    int maxArr = max(Arrays.stream(arr).toArray());
    System.out.println(maxArr);
}

public static void main(String[] args) {
    MyThread Thread1 = new MyThread();
    Thread1.start();
}

}

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

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