how to multithread in Java

依然范特西╮ 提交于 2019-12-04 16:50:43

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();

Put the batches in a BlockingQueue and make your worker threads to take the batches from the queue.

Use a lock or a mutex when retrieving the batch. That way, the threads can't access the critical section at the same time and can't accidentally access the same batch.

I'm assuming you're removing a batch once it was picked by a thread.

EDIT: aioobe and jonas' answers are better, use that. This is an alternative. :)

You need to synchronize the access to the list of jobs in the batch. ("Synchronize" essentially means "make sure the threads aware of potential race-conditions". In most scenarios this means "let some method be executed by a single thread at a time".)

This is easiest solved using the java.util.concurrent package. Have a look at the various implementations of BlockingQueue for instance ArrayBlockingQueue or LinkedBlockingQueue.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!