Multithreaded execution where order of finished Work Items is preserved

后端 未结 9 1214
无人共我
无人共我 2021-02-01 08:28

I have a flow of units of work, lets call them \"Work Items\" that are processed sequentially (for now). I\'d like to speed up processing by doing the work multithreaded.

<
9条回答
  •  心在旅途
    2021-02-01 09:08

    You could launch a DoTask thread for every WorkItem. This thread processes the work. When the work is done, you try to post the item, synchronized on the controlling object, in which you check if it's the right ID and wait if not.

    The post implementation can be something like:

    synchronized(controllingObject) {
    try {
    while(workItem.id != nextId) controllingObject.wait();
    } catch (Exception e) {}
    //Post the workItem
    nextId++;
    object.notifyAll();
    }
    

提交回复
热议问题