[英]Thread or Separate Object instances?
My rule of thumb about using thread is: if multiple instances of the same object needs to run concurrently, use threads. 关于使用线程的经验法则是:如果同一对象的多个实例需要同时运行,请使用线程。 But I am facing the design choice issue in a scenario similar to the one I am describing below.
但是我在类似于下面描述的场景中面临设计选择问题。 Please help me clarify this once and for all:
请一劳永逸地帮助我澄清一下:
(Reusing the example from my previous post)
(重用我上一篇文章中的例子)
I have 5 Pen object instances, 100 Author threads, and 3 Paper object instances.我有5个Pen对象实例,100个Author线程和3个Paper对象实例。
Any number of Authors may be using any number of Pens to write on any given paper.任何数量的作者可能会使用任意数量的笔在任何给定的论文上书写。
I have created blocking queue to protect the Pen objects being accessed by Authors.我创建了阻塞队列来保护作者访问的Pen对象。
If all pens in the queue are used, Authors wait.如果使用队列中的所有笔,则作者等待。
The Pen instances take data from Author threads and append it to the (specified) Paper instance.Pen实例从Author线程获取数据并将其附加到(指定的)Paper实例。
After updating Paper instance, Pen also updates the invoking Author thread.更新Paper实例后,Pen还会更新调用Author线程。
Questions: 问题:
My first take would be that Authors are workers (ie possibly threads), while pen and paper are resources (ie no threads - only used by some workers). 我的第一个采取将是作者是工人 (即可能是线程),而笔和纸的资源 (即没有线程- 仅用于一些工人)。
I would refactor the design to move the functionality from Pens to Authors. 我会重构设计,将功能从笔转移到作者。 Also I would try to model Authors as
Callable
s (or Runnable
s if there is no need to return any result) instead of threads, and run them within the Executor
framework - this gives higher level abstractions to work with, resulting in cleaner and safer code. 此外,我会尝试将Authors建模为
Callable
s(或Runnable
s,如果不需要返回任何结果)而不是线程,并在Executor
框架内运行它们 - 这样可以提供更高级别的抽象,从而实现更清晰,更安全码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.