Running a task in parallel to another task

后端 未结 5 693
清歌不尽
清歌不尽 2020-12-10 09:23

I have the following Foo class that uses FooProcessor class. So what i want to do is, while running cp1 instance process method, in parallel I want

5条回答
  •  长情又很酷
    2020-12-10 10:21

    You can of course use plain and simple Threads
    If you know you need to add more methods to the processor class, and for a given instance of it to keep execution order - let's say you first run method foo, and then run method bar, and you want them to run asynchronously, but keep execution order (first foo, then bar), I would consider to use Active Object pattern.
    I recommend also using this approach because for the user of the processor class it will hide implementation details.
    In addition, consider providing a decorator/wrapper that will provide this async ability to your objects - this way you will be able to control which object is run asynchronously and which isn't, and you will not have to "pollute" your Processor class with code needed for asynchronous invocation.
    An example of usage in this case will be -

    AsyncProcessor ap  = new AsyncProcessor(p1);
    ap.process();  //executed asynchronously
    Proccessor p2 = new Processor();
    p2.process(); //executed synchronously
    



    Another apporach is to use as you mentioned, an executor - This can be achieved by implementing a thread pool and pushing "execution units to it".
    An execution unit will contain the target object (cp1, cp2, ...) and the method to execute (currently - only process)
    The threads will take "an execution unit" from the queue and run them.
    The implementation is similar to active object, but the "interface" for the user is different as it uses a "TaskExecutor" class to provide it "execution units"

提交回复
热议问题