下面是一个使用Java实现的Hazelcast分布式计算的示例代码:
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IExecutorService;
import com.hazelcast.core.Member;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
public class DistributedComputingDemo {
public static void main(String[] args) throws Exception {
// 创建Hazelcast实例
HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance();
// 获取分布式ExecutorService
IExecutorService executorService = hazelcastInstance.getExecutorService("myExecutor");
// 提交任务并获取结果
List<Future<Integer>> futures = new ArrayList<>();
for (int i = 0; i < 10; i++) {
SquareTask task = new SquareTask(i);
Future<Integer> future = executorService.submit(task);
futures.add(future);
}
// 输出每个任务的执行结果
for (int i = 0; i < 10; i++) {
Future<Integer> future = futures.get(i);
int result = future.get();
System.out.println("Task " + i + " 的平方值:" + result);
}
// 输出集群中的成员信息
List<Member> members = new ArrayList<>(hazelcastInstance.getCluster().getMembers());
System.out.println("集群中的成员信息:");
for (Member member : members) {
System.out.println(member);
}
// 关闭Hazelcast实例
hazelcastInstance.shutdown();
}
// 自定义任务,计算给定数字的平方值
static class SquareTask implements Callable<Integer>, Serializable {
private int number;
public SquareTask(int number) {
this.number = number;
}
@Override
public Integer call() throws Exception {
return number * number;
}
}
}
这个示例演示了如何使用Hazelcast进行分布式计算。它创建了一个Hazelcast实例,获取了分布式ExecutorService,并提交了10个计算平方值的任务。然后,它获取每个任务的执行结果并进行输出。最后,它还展示了如何获取集群中的成员信息并关闭Hazelcast实例。
您可以运行上述示例代码,观察任务在集群中的分布执行,并获取每个任务的执行结果。您还可以尝试添加更多的任务,或在集群中添加更多的节点,以观察分布式计算的效果。
标签:java,int,demo,Hazelcast,number,分布式计算,import From: https://www.cnblogs.com/lukairui/p/17450206.html