package util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class DualUtil {
public static <T> T get(long seconds, Callable<T> callable) {
final ExecutorService exec = Executors.newFixedThreadPool(1);
T result = null;
try {
Future<T> future = exec.submit(callable);
result = future.get(seconds, TimeUnit.SECONDS);
} catch (Exception e) {
}
// 关闭线程池
exec.shutdown();
return result;
}
public static boolean isReachable(String ip) {
try {
boolean reachable = false;
Process p = Runtime.getRuntime().exec("ping -n 1 " + ip);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
if (line.length() != 0)
sb.append(line + "\r\n");
}
reachable = sb.toString().contains("TTL");
br.close();
return reachable;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
Boolean b = get(1, new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return isReachable("192.168.2.129");
}
});
System.out.println(b);
// System.out.println(isReachable("192.168.2.119"));
}
}
HOW2J公众号,关注后实时获知最新的教程和优惠活动,谢谢。
提问之前请登陆
提问已经提交成功,正在审核。 请于 我的提问 处查看提问记录,谢谢
|