java中ping多个ip_在Java中ping多个服务器

本文展示了如何在Java中使用ExecutorService并发地ping多个IP地址。通过创建一个固定大小的线程池,为每个IP地址创建一个PingTask实例,并将它们提交到线程池。每个PingTask实现Callable接口,返回一个包含IP地址和可达性结果的PingResult对象。

如何在没有其他人建议的情况下不使用ProcessBuilder.

我有三个类 – PingParallel是我的主类,PingTask是每个线程执行的任务,PingResult是结果代码(我们还可以添加更多信息,状态消息等).

PingParallel

package com.test.thread;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

public class PingParallel {

public static void main(String[] args) {

int totalIps = 89;

ExecutorService executor = Executors.newFixedThreadPool(totalIps);

List> list = new ArrayList>();

Callable callable = null;

for(int i=0; i< totalIps; i++){

callable = new PingTask("127.0.0"+i); // Get the ipAddres buttons[i].getText());

Future future = executor.submit(callable);

list.add(future);

}

for(Future fut : list){

try {

System.out.println(new Date()+ "::"+fut.get());

} catch (Exception e) {

e.printStackTrace();

}

}

executor.shutdown();

}

}

PingTask

package com.test.thread;

import java.net.InetAddress;

import java.util.concurrent.Callable;

public class PingTask implements Callable {

private String ipAddress;

public PingTask(String ipAddress) {

this.ipAddress = ipAddress;

}

@Override

public PingResult call() {

InetAddress inet = null;

try {

inet = InetAddress.getByName(ipAddress);

int resultCode = inet.isReachable(5000) ? 0 : -1;

return new PingResult(ipAddress, resultCode);

} catch (Exception e) {

e.printStackTrace();

return new PingResult(ipAddress, -1);

}

}

}

PingResult

package com.test.thread;

public class PingResult {

private String ipAddress;

private int resultCode;

public PingResult(String ipAddress, int resultCode) {

this.ipAddress = ipAddress;

this.resultCode = resultCode;

}

public String getIpAddress() {

return ipAddress;

}

public int getResultCode() {

return resultCode;

}

public String toString() {

return "IpAddress :: "+ ipAddress + " Result Code : "+ resultCode;

}

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值