简体   繁体   中英

Parallel execution of a for loop in java

I have used the ExecutorService and FutureTask in java to perform a parallel operation in a for loop. Following is the code

package com.sample.threading.parallel;

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.FutureTask;

public class Combinations { 
   public static String[] fillArray(int range) {
        String a[] = new String[100];
        for (int i = ((10 * range) + 1); i < (10 * (range + 1)); i++) {
            a[i] = "Name " + i;
        }
        return a;
    }


    public static String[] futureFillArray() throws Exception {
        String a[] = new String[100];
        int threadNum = 2;
        ExecutorService executor = Executors.newFixedThreadPool(threadNum);
        List<FutureTask<String[]>> taskList = new ArrayList<FutureTask<String[]>>();

        FutureTask<String[]> futureTask = new FutureTask<String[]>(
                new Callable<String[]>() {
                    @Override
                    public String[] call() throws Exception {
                        return fillArray(0);
                    }
                });

        taskList.add(futureTask);
        executor.execute(futureTask);

        FutureTask<String[]> futureTask1 = new FutureTask<String[]>(
                new Callable<String[]>() {
                    @Override
                    public String[] call() throws Exception {
                        return fillArray(1);
                    }
                });

        taskList.add(futureTask1);
        executor.execute(futureTask1);

        FutureTask<String[]> futureTask2 = new FutureTask<String[]>(
                new Callable<String[]>() {
                    @Override
                    public String[] call() throws Exception {
                        return fillArray(2);
                    }
                });

        taskList.add(futureTask2);
        executor.execute(futureTask2);

        FutureTask<String[]> futureTask3 = new FutureTask<String[]>(
                new Callable<String[]>() {
                    @Override
                    public String[] call() throws Exception {
                        return fillArray(3);
                    }
                });

        taskList.add(futureTask3);
        executor.execute(futureTask3);

        for (int j = 0; j < threadNum; j++) {
            FutureTask<String[]> futureTaskF = taskList.get(j);
            a = futureTaskF.get();
        }
        executor.shutdown();
        return a;
    }
}

I know that i have to call the fillArray method 10 times but i have called only three times. The following is the execution class

package com.sample.threading.parallel;

import java.util.Calendar;

public class ExecuteCombinations {

    public static void main(String[] args) throws Exception {
         long timeStart = Calendar.getInstance().getTimeInMillis();
            String res[] = Combinations.fillArray(0);
            long timeEnd = Calendar.getInstance().getTimeInMillis();
            long timeNeeded = timeEnd - timeStart;
            System.out.println("Result         : " + res + " calculated in " + timeNeeded + " ms");

            // Parallel execution
            long timeStartFuture = Calendar.getInstance().getTimeInMillis();
            String res2[] = Combinations.futureFillArray();
            long timeEndFuture = Calendar.getInstance().getTimeInMillis();
            long timeNeededFuture = timeEndFuture - timeStartFuture;
            System.out.println("Result (Future): " + res2 + " calculated in " + timeNeededFuture + " ms");
    }
}

but still the following is the output

Result         : [Ljava.lang.String;@773d3f62 calculated in 0 ms
Result (Future): [Ljava.lang.String;@47b6617 calculated in 16 ms

Is my implementation wrong? Please advise

I'm not sure if I understood you correctly. You're wondering why you only get two lines of output despite running 3 Futures, right? If that's the case, you only have to adjust the printing of your String res2[] = Combinations.futureFillArray(); (ie using a for -loop iterating over all the entries in res2[] to see all the results.

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