Java中如何实现多线程
我必须对一个以 1000 个批次运行代码的方法进行多线程处理。我需要将这些批次分配给不同的线程。
目前我已经生成了 3 个线程,但所有 3 个线程都选择了第一批 1000 个线程。 我希望其他批次不应该选择同一批次,而是选择其他批次。
请大家帮忙并提出建议。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会使用 ExecutorService
I would use an ExecutorService
将批次放入
BlockingQueue
并使工作线程从队列中获取批次。
Put the batches in a
BlockingQueue
and make your worker threads to take the batches from the queue.检索批次时使用
锁
或互斥体
。这样,线程就无法同时访问临界区,也不会意外访问同一批。我假设您在线程选择批次后将其删除。
编辑:aioobe 和 jonas 的答案更好,使用它。这是一个替代方案。 :)
Use a
lock
or amutex
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. :)
您需要同步对批次中作业列表的访问。 (“同步”本质上意味着“确保线程意识到潜在的竞争条件”。在大多数情况下,这意味着“让某个方法一次由一个线程执行”。)
这是最容易解决的问题,使用 java .util.concurrent 包。查看
的各种实现BlockingQueue
例如ArrayBlockingQueue
或LinkedBlockingQueue
。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 ofBlockingQueue
for instanceArrayBlockingQueue
orLinkedBlockingQueue
.