线程还是单独的对象实例?
我关于使用线程的经验法则是:如果同一对象的多个实例需要同时运行,请使用线程。但我在类似于我下面描述的场景中面临着设计选择问题。请帮我一劳永逸地澄清这一点:
(重用我之前的示例 post)
我有 5 个 Pen 对象实例, 100 个作者线程和 3 个 Paper 对象 实例。
任意数量的作者都可以 使用任意数量的笔书写 在任何给定的纸张上。
我已经创建了 阻塞队列来保护Pen 作者正在访问的对象。
如果队列中的所有笔都已使用, 作者们等等。
Pen 实例需要 来自作者线程的数据并将其附加 到(指定的)Paper 实例。
更新 Paper 实例后,Pen 还更新调用作者 线程。
问题:
- 运行钢笔是否有价值 对象作为线程?
- 如果是这样,我将如何传递数据 作者线程到钢笔线程,以便 Pen线程可以执行读取 (来自作者),写入(到 Paper),以及 回写(返回调用作者 线程)安全吗?
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.
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.
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.
After updating Paper instance, Pen
also updates the invoking Author
thread.
Questions:
- Is there value in running the Pen
object as threads? - If so, how would I pass data from
Author thread to Pen thread so that
the Pen thread can execute the read
(from author), write (to Paper), and
write back (back to invoking Author
thread) safely?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的第一个想法是,作者是工人(即可能是线程),而笔和纸是资源(即没有线程 - 仅由使用一些工人)。
我会重构设计,将功能从 Pens 转移到 Authors。另外,我会尝试将作者建模为
可调用
(或Runnable
(如果不需要返回任何结果)而不是线程,并在Executor
框架 - 这提供了更高级别的抽象来使用,从而产生更干净、更安全的代码。My first take would be that Authors are workers (i.e. possibly threads), while pen and paper are resources (i.e. 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 (orRunnable
s if there is no need to return any result) instead of threads, and run them within theExecutor
framework - this gives higher level abstractions to work with, resulting in cleaner and safer code.