• 大小: 3KB
    文件类型: .zip
    金币: 2
    下载: 1 次
    发布日期: 2021-06-05
  • 语言: Java
  • 标签:

资源简介

最近想写一个识别线程死锁的算法,在网上找了半天没有合适的代码,自己写了个查找有向图中的环的代码(可以将死锁的资源依赖建模成含环的有向图)。本代码经过充分测试,内部有详细说明,可以放心下载。

资源截图

代码片段和文件信息

package test.suanfa.findcycle2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

/**
 * @author [QQ:371319819]
 *
 */
public class Graph 
{
private List vertexList = new ArrayList(); // 节点集合
private Map> adjMat = new HashMap();      // 边关系集合
private Stack theStack = new Stack();
  
public void addVertex(String lab)
{
vertexList.add(new Vertex(lab));
}

/**
 * 边连接
 * 
 * @param start
 * @param end
 */
public void addEdge(String startNode String endNode)
{
List nextNodeList = adjMat.get(startNode);
if (nextNodeList == null)
{
nextNodeList = new ArrayList();
adjMat.put(startNode nextNodeList);
}

for (String oneNextNodeLabel : nextNodeList)
{
if (oneNextNodeLabel.equals(endNode))
{
return;
}
}

nextNodeList.add(endNode);
}

/**
 * 如果一条路径,在旧有的所有路径中都不存在,则代表是一条新路径,可以继续 遍历:不依靠节点的是否已访问标志来识别当前路径是否可选,
 * 在遍历路径中带环的图有效果
 * 
 * @param nextEnd
 * @param curPath
 * @param allPath
 * @return
 */
public boolean existPath(String nextEnd List curPath List> allPath)
{
String head = curPath.get(0);
List tmpPath = new ArrayList();
tmpPath.addAll(curPath);

if (nextEnd != null && !nextEnd.equals(““))
{
tmpPath.add(nextEnd);
}

for (List onePath : allPath)
{
if (!onePath.get(0).equals(head))
{
continue;
}

if (tmpPath.size() > onePath.size())
{
continue;
}

int sameCount = 0;
for (int i = 0; i < tmpPath.size(); i++)
{
if (tmpPath.get(i).equals(onePath.get(i)))
{
sameCount++;
}
}

if (sameCount == tmpPath.size())
{
return true;
}
}

return false;
}

/**
 * 深度优先遍历
 * 目前只选中一个节点作为开始节点来遍历出所有路径,如果希望遍历所有路径,可以在本方法外部增加一个for循环
 * 
 */
public List> mst()  // minimum spanning tree (depth first)
{        
Vertex firstVertex = vertexList.get(0);
    theStack.push(firstVertex);

    List> allPathList = new ArrayList();
    List onePath = new ArrayList();
    onePath.add(firstVertex.label);
    allPathList.add(onePath);
    
    while(!theStack.isEmpty() )       // until stack empty
    {                               // get stack top
     Vertex currentVertex = theStack.peek();
     String currentVertexLabel = currentVertex.label;
     // 如果在for循环中没有找到后续的节点,也要后退一个节点
     Vertex nextNode = null;
    
     boolean cycleEnd = false;
     boolean existPath = false;
    
     List nextNodeList = adjMat.get(currentVertexLabel);
     if (nextNodeList != null && !nextNodeList.isEmpty())
     {
        for(String oneNextNodeLabel : nextNodeList)
{
cycleEnd = false;
         existPath = false;
        
if (existPath(oneNextNodeLabel onePat

 属性            大小     日期    时间   名称
----------- ---------  ---------- -----  ----
     文件        5840  2015-11-12 21:12  Graph.java
     文件        2607  2015-11-12 21:07  MSTApp.java
     文件         144  2015-11-12 21:07  Vertex.java

评论

共有 条评论

相关资源