Search code examples
javamultithreadingmergesortjava-threads

How can I see if my code actually makes use of multithreading?


I've been trying to write a Merge Sort algorithm in Java to make use of Multithreading and I'm stuggling to see actually if my code makes use of multithreading, or if I'm just sequentially making thread objects which then go and run the recursive merge sort call?

The Merge sort is as follows:

public class Sort {

    public int[] mergeSort(int[] myItems) {

        Splice splicer = new Splice();

        if (myItems.length < 2) {
            return myItems;
        }

        int mid = myItems.length / 2;

        //splits the load of each recursive call to different threads to run at the same time
        int[] left = new Multi(splicer.splice(myItems, 0, mid-1)).doSort();
        int[] right = new Multi(splicer.splice(myItems, mid, myItems.length -1)).doSort();
        
        ...
        return myItems
   }
}

The class for the thread is:

public class Multi extends Thread {

    Sort merge = new Sort();
    private int[] myItems;

    public Multi(int[] myItems) {
        this.myItems = myItems;
    }

    public void run() {
    }

    public int[] doSort() {
        return merge.mergeSort(myItems);
    }

}

(splice is a function I've made which takes the array, the start index and the final index and outputs the elements within the given range as a new array)

TLDR: by making use of a thread class, will the program do multithreading or is it just a long winded way of calling the function again.


Solution

  • Your thread is not started. If you call the .start() method, then your thread will be started and the contents of your .run() method will be executed. Since your .run() method is empty, your thread will be short-lived. You will nee to refactor your thread like

    public class Multi extends Thread {
    
        Sort merge = new Sort();
        private int[] myItems;
        protected int[] result;
    
        public Multi(int[] myItems) {
            this.myItems = myItems;
        }
    
        public void run() {
            result = doSort();
        }
    
        public void doSort() {
            return merge.mergeSort(myItems);
        }
    
        public int[] getResult() {
            return result;
        }
    
    }
    

    and, insteat of calling .doSort() directly, store your Multi object into a variable, like this:

    Multi multiLeft = new Multi(splicer.splice(myItems, 0, mid-1));
    Multi multiRight = new Multi(splicer.splice(myItems, mid, myItems.length -1));
    

    and then call multiLeft.start(); and multiRight.start();. Don't forget to .join() them before you call multiLeft.getResult() and multiRight.getResult(), respectively.