I am trying to code a problem in Java where I have to execute a bunch of tasks.
Problem
Execute a job which consists of multiple tasks and thos
Your problem looks like a good use case for Java's ForkJoin Framework. You could implement your tasks as RecursiveActions or RecursiveTasks (depending on whether you need a return value or not) which will start their sub tasks on whatever condition you need. You'll also be able to control if your sub tasks run sequentially or in parallel.
Example:
public class TaskA extends RecursiveAction {
// ...
protected void compute() {
if (conditionForTaskM) {
TaskM m = new TaskM();
// Run task M asynchronously or use m.invoke() to run it synchronously.
invokeAll(m);
}
// Run task N at the end of A
invokeAll(new TaskN());
}
}
You need an instance of the ForkJoinPool to run your tasks:
public static void main(String[] args) {
ForkJoinPool pool = new ForkJoinPool();
pool.submit(new TaskA());
// Properly shutdown your pool...
}
This example is quite simplistic in implementing a part of your example problem. But generally speaking, the ForkJoin Framework allows you to create tree-like structures of tasks where every parent task (such as A, B and P) allows you to control the execution of its immediate child tasks.