Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Main {
    public static long pmax(final long[][] arr, int numThreads) {
        ExecutorService pool = Executors.newFixedThreadPool(numThreads);
        try {
            List<Future<Long>> list = new ArrayList<Future<Long>>();
            for (int i = 0; i < arr.length; i++) {
                final long[] subArr = arr[i];
                list.add(pool.submit(new Callable<Long>() {
                    public Long call() {
                        long max = Long.MIN_VALUE;
                        for (int j = 0; j < subArr.length; j++) {
                            if (subArr[j] > max) {
                                max = subArr[j];
                            }
                        }
                        return max;
                    }
                }));
            }
            // find the max of each slice's max:
            long max = Long.MIN_VALUE;
            for (Future<Long> future : list) {
                long threadMax = future.get();
                System.out.println("threadMax: " + threadMax);
                if (threadMax > max) {
                    max = threadMax;
                }
            }
            return max;
        } catch (Exception e) {
            System.out.println(e);
            return -1;
        } finally {
            pool.shutdown();
        }
    }

    public static void main(String args[]) {
        long[][] data = new long[1000][1000];
        for (int i = 0; i < 1000; i++) {
            for (int j = 0; j < 1000; j++) {
                data[i][j] = i * j * j;
            }
        }
        int numThreads = 32;
        long pmax = pmax(data, numThreads);
        System.out.println("pmax: " + pmax);
    }
}