DAG Task 任务调度算法 实现
github:https://github.com/smartxing/algorithm
1 有向图的构建
DAG dag = new DAG();
dag.addVertex("A");
dag.addVertex("B");
dag.addVertex("C");
dag.addVertex("D");
dag.addEdge("A", "B");
dag.addEdge("A", "C");
System.out.println(dag);
2 拓扑排序检测图中是否有环
public boolean isCircularity() {
Set set = inDegree.keySet();
//入度表
Map inDegree = set.stream().collect(Collectors
.toMap(k -> k, k -> new AtomicInteger(this.inDegree.get(k).size())));
//入度为0的节点
Set sources = getSources();
LinkedList queue = new LinkedList();
queue.addAll(sources);
while (!queue.isEmpty()) {
Object o = queue.removeFirst();
outDegree.get(o)
.forEach(so -> {
if (inDegree.get(so).decrementAndGet() == 0) {
queue.add(so);
}
});
}
return inDegree.values().stream().filter(x -> x.intValue() > 0).count() > 0;
}
3 stage优化
eg
如果任务存在如下的关系 , task1 执行完后执行 task2 ,task2 执行完后执行task3 ...
Task1 -> Task2 -> Task