-5

I have create a program to split an array into two arrays, then sort them after that merge them back together.

My program works perfectly when I invoke run() directly, but when I use start() I get a NullPointerException.

Can anyone tell me how to fix this?

public class SortingClass extends Thread{
    public int[] arr, arr0;

    public SortingClass(int[] a){
        this.arr = a;
    }

    @Override
    public void run() {
        this.arr0 = sorting(arr);
    }

    public int[] sorting(int[] a){
        int value;
        int j;

        for (int i = 1; i < a.length; i++){
            value = a[i];
            j = i-1;

            while( j>=0 && a[j]>value ){
                a[j+1] = a[j];
                j = j-1;
            }
            a[j+1] = value;
        }
        return a;
    }

    public static int[] merge(int[] A, int[] B) {
        int size = A.length + B.length;
        int C [] = new int [size];
        int i, a = 0, b = 0;

        for(i=0; i<size; i++){
            if(a == A.length){
                C[i] = B[b];
                ++b;
            } else if(b == B.length){
                C[i] = A[a];
                ++a;
            } else if(A[a] > B[b]) {
                C[i]=B[b];
                ++b;
            } else {
                C[i] = A[a];
                ++a;
            }
        }

        return C;
    }

    public static void print(int[] a, int[] b){
        System.out.println("Before \t After");
        for (int i = 0; i < a.length; i++) {
            System.out.printf("%d \t %d\n",a[i],b[i]);
        }      
    }

    public static void main(String[] args) {
        int[] arr = new int[10];
        int[] arr0;
        Random r = new Random();

        for(int i = 0; i<arr.length; i++){
            //arr[i] = r.nextInt(100);
            arr[i] = i;
        }

        int[] arr1,arr2;
        arr1 = new int[arr.length/2];
        arr2 = new int[arr.length/2];

        int i = 0;
        int j = 0;
        while(i<arr.length){
            if (i < arr.length/2){
                arr1[i] = arr[i];
            } else {
                arr2[j] = arr[i];
                j++;
            }
            i++;    
        }

        SortingClass s1 = new SortingClass(arr1);
        SortingClass s2 = new SortingClass(arr2);

        s1.start();
        s2.start();

        arr0 = merge(s1.arr0,s2.arr0);
        print(arr, arr0);
    }
}
4

1 回答 1

8

您在merge()线程完成运行之前调用。
因此,arr0为空。

您需要通过调用等待每个线程完成.join()

当您调用 时.run(),您直接在调用线程中运行该方法(与任何其他方法调用一样,并且不涉及Thread),因此没有任何问题。

于 2013-07-22T18:31:00.007 回答