简体   繁体   中英

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.
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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM