简体   繁体   中英

multiple threads that search a section of an array

i am given the following code that makes a large array and finds that max value.

import java.util.Date;
import java.util.Random;

class FindMax {
private static final int N = 256 * 1024 * 1024;

public static void main(String args[]) {
    assert(N > 0);

    int array[] = new int [N];

    assert(array != null);

    Random random = new Random(new Date().getTime());

    for (int i = 0; i < N; i++) {
        array[i] = random.nextInt();
    }

    Date start = new Date();

    int max = array[0];

    for (int i = 1; i < N; i++) {
        if (array[i] > max) {
            max = array[i];
        }
    }

    Date end = new Date();

    System.out.println("max: " + max);
    System.out.println("time in msec: " + (end.getTime() - start.getTime()));
}
}

I am to alter the code to make it faster by making multiple threads that each find the max value of a section of the array and then the main thread find the max value of the max values found by the threads. This is what i have come up with so far.

import java.util.Date;
import java.util.Random;

class FindMax extends Thread{
private static final int N = 256 * 1024 * 1024;

static int array[] = new int [N];
static int max = array[0];

public void run(){
    for (int i = 1; i < N; i++) {
        if (array[i] > max) {
            max = array[i];
        }
    }

}

public static void main(String args[]) {
    assert(N > 0);
    int ts = Integer.parseInt(args[0]);


    assert(array != null);

    Random random = new Random(new Date().getTime());

    for (int i = 0; i < N; i++) {
        array[i] = random.nextInt();
    }

    Date start = new Date();

    Thread t[] = new Thread[ts];
    for( int p=0; p<ts;p++){
        t[p] = new FindMax();
        t[p].start();
    }





    Date end = new Date();

    System.out.println("max: " + max);
    System.out.println("time in msec: " + (end.getTime() - start.getTime()));
}
}

i am not understanding this, so what am i doing wrong?

You're off to a good start. The next thing you need to do is give the FindMax class two member variables to represent the beginning and end of the range to search. Use those two member variables in place of 1 and N in the for loop. Then give FindMax a constructor with which you can set the two values. Then in the loop that constructs the FindMax objects, give each one a unique range to search. Finally, give FindMax a member variable to store the max value in, so that main() can query the max value found by each FindMax .

You'll probably want to use the join() method of the Thread class -- it waits for a Thread to finish before returning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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