今天写了一个模拟分布式系统中的节点和协调者的行为,并实现了协调者崩溃后的新协调者选举机制。
import java.util.Random;
import java.util.ArrayList;
import java.util.List;
class Node implements Runnable {
private int nodeId;
private boolean isCoordinator;
private boolean isCrashed;
private Coordinator coordinator;
public Node(int nodeId, boolean isCoordinator, Coordinator coordinator) {
this.nodeId = nodeId;
this.isCoordinator = isCoordinator;
this.coordinator = coordinator; // 确保协调者对象被正确设置
}
public int getNodeId() {
return nodeId;
}
public boolean isCrashed() {
return isCrashed;
}
public boolean isCoordinator() {
return isCoordinator;
}
public void crash() {
isCrashed = true;
}
public void setCoordinator(Coordinator coordinator) {
this.coordinator = coordinator;
}
public void run() {
if (isCoordinator) {
while (true) {
synchronized (coordinator) {
// 临界资源的访问逻辑
System.out.println("协调者节点" + nodeId + "管理临界资源");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} else {
while (true) {
synchronized (coordinator) {
// 随机访问协调者的计数器
System.out.println("节点" + nodeId + "访问协调者节点的计数器");
try {
Thread.sleep(new Random().nextInt(2000) + 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class Coordinator {
private int counter;
public Coordinator(int initialCounter) {
this.counter = initialCounter;
}
public int getCounter() {
return counter;
}
public void incrementCounter() {
counter++;
}
}
public class DistributedSystem {
public static void main(String[] args) {
int nodeCount = 5;
List<Node> nodes = new ArrayList<>();
Coordinator coordinator = null;
// 初始化节点
for (int i = 0; i < nodeCount; i++) {
Node node;
if (i == nodeCount - 1) {
// 节点号最大者为协调者
coordinator = new Coordinator(0);
node = new Node(i, true, coordinator); // 传入协调者对象
} else {
node = new Node(i, false, coordinator); // 传入协调者对象
}
nodes.add(node);
}
// 启动节点线程
for (Node node : nodes) {
Thread thread = new Thread(node);
thread.start();
}
// 模拟协调者崩溃
nodes.get(nodeCount - 1).crash();
// 选举新的协调者
int maxNodeId = -1;
Node newCoordinator = null;
for (Node node : nodes) {
if (!node.isCrashed() && node.getNodeId() > maxNodeId) {
maxNodeId = node.getNodeId();
newCoordinator = node;
}
}
if (newCoordinator != null) {
newCoordinator.setCoordinator(new Coordinator(coordinator.getCounter()));
}
// 输出新的协调者信息
if (newCoordinator != null) {
System.out.println("新的协调者节点为 " + newCoordinator.getNodeId());
}
}
}