簡體   English   中英

將每個線程分配一個特定范圍

[英]Distributing each thread a Particular Range

我在多線程程序中使用ThreadPoolExecutor,如果ThreadSize is set as 10Start = 1 and End = 1000則每個線程應具有特定的ID范圍,然后每個線程將具有100個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);
    }
}

不管這是一個好主意,我都會讓您決定。 但是為了幫助您,我編寫了一個小程序,該程序可以滿足您的需求……就我而言,我只是在總結“ id”。

這是代碼:

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;
    }

}

}

它將產生以下輸出(請注意,以真正的多線程方式,您具有隨機順序的打印語句,因為以系統決定的順序執行線程):

線程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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM