Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>So a thread pool may or may not be the best usage here because there is no real abstraction of work. However this may an interesting use case for extending Thread. I would handle the communication with simple j.u.c.Lock and j.u.c.Condition. Finally, I would delegate stopping and starting to specific delegation classes that accept a Runnable type as individual constant units of work. </p> <p>The only difference I would is to use stop to shutdown and pause to suspend which the start will just continue the work. For example it could look something like this.</p> <pre><code>public class MedicalDeviceWorkManager { private ConcurrentHashMap&lt;String, DelegatingThread&gt; devices = new ConcurrentHashMap&lt;...&gt;(); public synchronized void registerDevice(String device, Runnable singleUnitOfWork){ DelegatingThread worker = new DelegatingThread(singleUnitOfWork); devices.put(device,worker); worker.start(); } public void startDevice(String device){ devices.get(device).startDevice(); } public void stopDevice(String device){ devices.get(device).stopDevice(); } public void pauseDevice(String device){ devices.get(device).pauseDevice(); } private static class DelegatingThread extends Thread{ final Lock lock = new ReentrantLock(); final Condition condition = lock.newCondition(); final Runnable r; boolean paused = true; boolean stopped =false; private DelegatingThread (Runnable r){ this.r = r; } @Override public void run(){ while(true){ lock.lock(); while(paused) condition.await(); if(stopped) return; lock.unlock(); r.run(); } } private void startDevice(){ lock.lock(); paused = false; condition.signal(); lock.unlock(); } private void pauseDevice(){ lock.lock(); if(!stopped) paused = true; lock.unlock(); } private void stopDevice(){ lock.lock(); stopped= true; paused=false; condition.signal(); lock.unlock(); } } } </code></pre> <p>I understand this is a lot of code to demonstrate but the same principles behind a thread pool holds here. You will always create one thread per device and you reuse when necessary. The runnable would be the single function you run in between the while loop. </p> <p>Also, I didn't include the try/finally semantics for brevity.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload