java - Can I redirect a worker thread to do a different job in middle of processing? -
i have worker class use multithreading.
public class worker extends swingworker<void , string> {     private int optionofwork;     public worker(int int optionofwork)     {         this.optionofwork = optionofwork;     }     ...     ...     protected void doinbackground() throws exception     {         switch (optionofwork) {             case 1:             {                 ...                 ...                 break;             }             case 2:             {                 ...                 something...             }             default:             {                 ...             }         }      }//doinbackground()  }//worker class     say create worker thread instance:
worker worker1 = new worker(1);   and start using worker1.excute();
 worker starts doinbackground() method in case of optionofwork = 1.     
can change (from main thread) worker's job in middle of excution this:
worker1.setoptionofwork(2); worker1.excute();       or maybe:
worker1.setoptionofwork(2); worker1.doinbackground();    and stop it's current excution , start excuting case: optionofwork = 2 of doinbackground() method?
there misconception on end. when main thread call:
worker1.setoptionofwork(2); worker1.doinbackground();    then work done on main thread. precise: thread invoking methods spends time "doing" work then.
but beyond that: of course possible. your worker implementation, you in full control. have understand: in order "correct" (and reasonable "architected") - lot of work required:
- you need appropriate data structure communicate worker threads (for example queue)
 - your worker threads need periodically check status of queue
 - and there: if want "change" happening, main thread puts in "command" queue. worker thread reads command, , acts accordingly.
 
as can see, "flow" pretty simple - requires quite implementation effort (and easy wrong).
in sense, recommendation is: if threads doing work want "cancel" them - create smaller work packages. instead of having 1 thread being busy 1 task 10 minutes - create many smaller tasks. , add execution. "cancel" means - not sending further "small" requests.
such architecture easier implement, , more robust in long run.
Comments
Post a Comment