public class SpanTree extends Process {
public int parent = -1; // no parent yet
public IntLinkedList children = new IntLinkedList();
int numReports = 0;
boolean done = false;
public SpanTree(Linker initComm, boolean isRoot) {
super(initComm);
if (isRoot) {
parent = myId;
if (initComm.neighbors.size() == 0)
done = true;
else
sendToNeighbors( "invite", myId);
}
}
public void waitForDone() { // block till children known
while (!done) myWait();
}
public synchronized void handleMsg(Message m, int source, String tag) {
if (tag.equals("invite")) {
if (parent == -1) {
numReports++;
parent = source;
sendMsg(source, "accept");
Util.println("Sending accept");
for (int i = 0; i < N; i++)
if ((i != myId) && (i != source) && isNeighbor(i))
sendMsg(i, "invite");
} else
sendMsg(source, "reject");
} else if ((tag.equals("accept")) || (tag.equals("reject"))) {
if (tag.equals("accept")) children.add(source);
numReports++;
if (numReports == comm.neighbors.size()) {
done = true;
notify();
}
}
}
}