0

マルチスレッドプログラムでThreadPoolExecutorを使用しています。各スレッドに、他のスレッドを踏まずThreadSize is set as 10Start = 1 and End = 1000使用できる100 IDの範囲(基本的には終了範囲をスレッドサイズで除算)のIDの範囲を指定する必要があります。

Thread1 will use 1 to 100 (id's)

Thread2 will use 101 to 200 (id's)

Thread3 will use 201 to 300 (id's)
-----
-----
Thread10 will use 901 to 1000

私は基本的にロジックを知っています、ロジックはこのようにすることができます-

Each thread gets `N = (End - Start + 1) / ThreadSize` numbers.

Thread number `i` gets range `(Start + i*N) - (Start + i*N + N - 1)`.

ThreadPoolExecutorを初めて使用するため、コード内でこのロジックをどこで使用すればよいかわからないため、各スレッドは他のスレッドを踏まずに事前定義されたIDを使用します。任意の提案をいただければ幸いです。

public class CommandExecutor {

    private List<Command> commands;
    ExecutorService executorService;
    private static int noOfThreads = 3;

    // Singleton
    private static CommandExecutor instance;
    public static synchronized CommandExecutor getInstance() {
        if (instance == null) {
            instance = new CommandExecutor();
        }
        return instance;
    }

    private CommandExecutor() {

        try {
            executorService = Executors.newFixedThreadPool(noOfThreads);
        } catch(Exception e) {
            System.out.println(e);
        }
    }

    // Get the next command to execute based on percentages
    private synchronized Command getNextCommandToExecute() {

    }

    // Runs the next command
    public synchronized void runNextCommand() {
        // If there are any free threads in the thread pool
        if (!(((ThreadPoolExecutor) executorService).getActiveCount() < noOfThreads))
            return;
        // Get command to execute
        Command nextCommand = getNextCommandToExecute();
        // Create a runnable wrapping that command
        Task nextCommandExecutorRunnable = new Task(nextCommand);
        executorService.submit(nextCommandExecutorRunnable); // Submit it for execution
    }

    // Implementation of runnable (the real unit level command executor)
    private static final class Task implements Runnable {
        private Command command;
        public Task(Command command) {
            this.command = command;
        }
        public void run() {
            // Run the command
            command.run();
        }
    }

    // A wrapper class that invoked at every certain frequency, asks CommandExecutor to execute next command (if any free threads are available)
    private static final class CoreTask implements Runnable {
        public void run() {
            CommandExecutor commandExecutor = CommandExecutor.getInstance();
            commandExecutor.runNextCommand();
        }
    }

    // Main Method
    public static void main(String args[]) {
        // Scheduling the execution of any command every 10 milli-seconds
        Runnable coreTask = new CoreTask();
        ScheduledFuture<?> scheduledFuture = Executors.newScheduledThreadPool(1).scheduleWithFixedDelay(coreTask, 0, 10, TimeUnit.MILLISECONDS);
    }
}
4

1 に答える 1

0

これが良い考えであるかどうかは、あなたが決めることを任せます。しかし、あなたに手を差し伸べるために、私はあなたが望むことをする小さなプログラムを書きました...私の場合、私は単に「ids」を要約しています。

コードは次のとおりです。

public class Driver {

private static final int N = 5;

public static void main(String args[]) throws InterruptedException, ExecutionException{
    int startId = 1;
    int endId = 1000;
    int range = (1 + endId - startId) / N;
    ExecutorService ex = Executors.newFixedThreadPool(N);
    List<Future<Integer>> futures = new ArrayList<Future<Integer>>(N);

    // submit all the N threads
    for (int i = startId; i < endId; i += range) {
        futures.add(ex.submit(new SumCallable(i, range+i-1)));
    }

    // get all the results
    int result = 0;
    for (int i = 0; i < futures.size(); i++) {
        result += futures.get(i).get();

    }
    System.out.println("Result of summing over everything is : " + result);

}

private static class SumCallable implements Callable<Integer> {

    private int from, to, count;
    private static int countInstance = 1;

    public SumCallable(int from, int to) {
        this.from = from;
        this.to = to;
        this.count = countInstance;
        System.out.println("Thread " + countInstance++ + " will use " + from + " to " + to);
    }

    // example implementation: sums over all integers between from and to, inclusive.
    @Override
    public Integer call() throws Exception {
        int result = 0;
        for (int i = from; i <= to; i++) {
            result += i;
        }
        System.out.println("Thread " + count + " got result : " + result);
        return result;
    }

}

}

これにより、次の出力が生成されます(真のマルチスレッド方式では、システムが決定した順序でスレッドが実行されるため、ランダムな順序でprintステートメントがあることに注意してください)。

スレッド1は1から200を使用します

スレッド2は201から400を使用します

スレッド1の結果:20100

スレッド3は401から600を使用します

スレッド2の結果:60100

スレッド4は601から800を使用します

スレッド3の結果:100100

スレッド5は801から1000を使用します

スレッド4の結果:140100

スレッド5の結果:180100

すべてを合計した結果は:500500

于 2012-05-17T23:48:21.720 に答える