Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7951173
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T02:28:56+00:00 2026-06-04T02:28:56+00:00

I am using ThreadPoolExecutor in my multithreading program, I want each thread should have

  • 0

I am using ThreadPoolExecutor in my multithreading program, I want each thread should have particular range of ID’s if ThreadSize is set as 10 and Start = 1 and End = 1000 then each thread would have range of 100 id’s(basically by dividing end range with thread size) that it can use without stepping on other threads.

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

I know the logic basically, the logic can be like this-

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

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

As I am working with ThreadPoolExecutor for the first time, so I am not sure where should I use this logic in my code so that each Thread is Using a predefined ID’s without stepping on other threads. Any suggestions will be appreciated.

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);
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T02:28:58+00:00Added an answer on June 4, 2026 at 2:28 am

    Whether this is a good idea or not I will leave it for you to decide. But to give you a hand, I wrote a little program that does what you want… in my case I am just summing over the “ids”.

    Here is the code:

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

    }

    which produces the following output (notice that in true multi-thread fashion, you have print statements in random order, as the threads are executed in whatever order the system decides):

    Thread 1 will use 1 to 200

    Thread 2 will use 201 to 400

    Thread 1 got result : 20100

    Thread 3 will use 401 to 600

    Thread 2 got result : 60100

    Thread 4 will use 601 to 800

    Thread 3 got result : 100100

    Thread 5 will use 801 to 1000

    Thread 4 got result : 140100

    Thread 5 got result : 180100

    Result of summing over everything is : 500500

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a thread pool created using java.util.concurrent.ThreadPoolExecutor Is there anyway I can wait
I have my Batch Application Program, in which I am using ThreadPoolExecutor in my
I've been messing around with different strategies for thread pooling using ThreadPoolExecutor with JDK6.
I am using the ThreadPoolExecutor to implement threading in my Java Application. I have
i am using a ThreadPoolExecutor with a thread pool size of one to sequentially
Using Nunit, I want to be able to write a test fixture that will
Using C# for ASP.NET and MOSS development, we often have to embed JavaScript into
I have a Runnable running inside a ThreadPoolExecutor long polling on an http request
I want to be executing some different tasks in parallel, but have the concept
What is the best way to handle RejectedExecutionException while using a ThreadPoolExecutor in Java?

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.