Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
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;
import java.util.concurrent.ThreadFactory;

public class Main {
    static <T> List<T> submit(List<? extends Callable<T>> taskList, final String taskName) throws Exception {

        List<Future<T>> futureList = new ArrayList();

        List<T> result = new ArrayList<>();

        ExecutorService pool = newFixedThreadPool(taskList.size(), taskName);

        for (Callable<T> callable : taskList) {
            futureList.add(pool.submit(callable));
        }

        pool.shutdown();

        for (Future<T> f : futureList) {
            try {
                result.add(f.get());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    static ExecutorService newFixedThreadPool(int size, final String threadNamePrefix) {

        return Executors.newFixedThreadPool(size, new ThreadFactory() {

            int threadIdx = 0;

            public Thread newThread(Runnable r) {
                return new Thread(r, threadNamePrefix + threadIdx++);
            }
        });
    }
}