Search code examples
javamultithreadingsynchronize

how to multithread in Java


I have to multithread a method that runs a code in the batches of 1000 . I need to give these batches to different threads .

Currently i have spawn 3 threads but all 3 are picking the 1st batch of 1000 . I want that the other batches should not pick the same batch instead pick the other batch .

Please help and give suggestions.


Solution

  • I would use an ExecutorService

    int numberOfTasks = ....
    int batchSize = 1000;
    ExecutorService es = Executors.newFixedThreadPool(3);
    for (int i = 0; i < numberOfTasks; i += batchSize) {
        final int start = i;
        final int last = Math.min(i + batchSize, numberOfTasks);
        es.submit(new Runnable() {
            @Override
            public void run() {
                for (int j = start; j < last; j++)
                    System.out.println(j); // do something with j
            }
        });
    }
    es.shutdown();