Running a task in parallel to another task

后端 未结 5 690
清歌不尽
清歌不尽 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:05

    The way I would implement it, in summary :

    • run your different processes via an ExecutorService, for example ExecutorService executor = Executors.newFixedThreadPool(nThreads);
    • store the Futures of all your tasks in a List (returned by ExecutorService#submit)
    • wait for future1.get() to complete, where future1 is the future linked to cp1
    • once get returns (cp1 has finished) cancel all the other futures, (or shutdownNow the executor service if you don't need the executor any longer)
    • for that cancellation process to work, your cp2, cp3 etc need to implement an interruption policy that makes them stop what they are doing asap.

提交回复
热议问题