-1

I've a piece of code that I've been working on in order to find max element in an array using threads. I've successfully done it to sum the element of an array but I've faced few problems figuring how to find the max. Also, I didn't know how to use the override run method in this case !. I'm using Java obviously.

public class maxUsingThread extends Thread {
    private int lo, hi;
    private int[] arr;
    private static int maxInArr;
    private static int[] maxArr;

    public maxUsingThread(int[] arr, int lo, int hi) {
        this.lo = lo;
        this.hi = hi;
        this.arr = arr;
    }

    public static int max(int[] arr) throws InterruptedException {
        int len = arr.length;
        maxUsingThread[] ts = new maxUsingThread[4];
        for (int i = 0; i < 4; i++) {
            ts[i] = new maxUsingThread(arr, (i * len) / 4, ((i + 1) * len / 4));
            ts[i].start();
        }

        maxArr = new int[4];
        int max = arr[0];
        for (int i = 0; i < 4; i++) {
            ts[i].join();
            for (int j = 1; j < len; j++) {      
                if ( max < arr[i] ){
                    max = arr[i];
                    for (int k = 0; k < 4; k++) {
                        maxArr[0] = max;

                    }
                }     
            }
        }
        maxInArr = maxArr[0];
        for (int i = 1; i < 4; i++) {
            if (maxInArr < maxArr[i]){
                maxInArr = maxArr[i];
            }   
        }
        return maxInArr;
    }

    public static void main(String[] args) throws InterruptedException {
        int[] arr = new int[100];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = i;
        }
        int max = max(arr);
        System.out.println("Max: " + max);
    }
}

Your help will be appreciated, Thanks.

Thomas Böhm
  • 1,456
  • 1
  • 15
  • 27
Red John
  • 105
  • 3
  • 11
  • 2
    How to find the max element using threads? `int max = IntStream.of(arr).parallel().max().getAsInt();` – Elliott Frisch Nov 04 '17 at 16:30
  • Red John, is your goal to understand how threads work by writing your own threads or do you simply need a solution to the problem of finding the max in a multi-threaded way? – D.B. Nov 04 '17 at 16:36
  • This appears to be multiple questions in one - please explain what you've tried, and specifically where you're stuck. – Tyzoid Nov 04 '17 at 16:39
  • I appreciate your help, I understand how the code works but the thing is I couldn't figure out a solution, so the second part of your question is the answer. Tyzoid, I've tried to make each thread work on a specific part of my array to get the max and then to compare them, but I have no idea why it didn't work. – Red John Nov 25 '17 at 15:41

1 Answers1

1

try to find for each thread the max number, then the final result for each thread compare them and find the final max number.

Check this question, It is will help you a lot.

Zahoori Nazo
  • 53
  • 1
  • 10