Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 to run cp2.process().

public class Foo {

    public static void main(String [] args){

        FooProcessor cp1 = new FooProcessor();
        FooProcessor cp2 = new FooProcessor();

        cp1.process();
        // in parallel process cp2.process();
    }

}

public class FooProcessor {
    public void process(){
        System.out.println("Processing..");
    }
}

However, i want cp1 sequentially, so i want it to run and complete, if cp2 doesnt complete or fails it is fine. If it doenst fail i want to join the results. It is not returning anything in this sample but I want to return result.

For this purpose, should is use TaskExecutor? or Thread?

I want only cp2 to run in parallel to cp1. or if i add more lets say cp3, i want that to run in parallel as well to cp1.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
88 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...