Java總結篇系列:Java多執行緒(四)
阿新 • • 發佈:2019-02-16
多個執行緒同步執行ping ip示例
package com.ebao.pojo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainTestIP {
public static boolean ping(String ipAddress, int pingTimes, int timeOut) {BufferedReader in = null;
Runtime r = Runtime.getRuntime(); // 將要執行的ping命令,此命令是windows格式的命令
String pingCommand = "ping " + ipAddress + " -n " + pingTimes + " -w " + timeOut;
try { // 執行命令並獲取輸出
System.out.println(pingCommand);
Process p = r.exec(pingCommand);
if (p == null) {
return false;
}
in = new BufferedReader(new InputStreamReader(p.getInputStream())); // 逐行檢查輸出,計算類似出現=23ms TTL=62字樣的次數
int connectedCount = 0;
String line = null;
while ((line = in.readLine()) != null) {
connectedCount += getCheckResult(line);
} // 如果出現類似=23ms TTL=62這樣的字樣,出現的次數=測試次數則返回真
return connectedCount == pingTimes;
} catch (Exception ex) {
ex.printStackTrace(); // 出現異常則返回假
return false;
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//若line含有=18ms TTL=16字樣,說明已經ping通,返回1,否則返回0.
private static int getCheckResult(String line) { // System.out.println("控制檯輸出的結果為:"+line);
Pattern pattern = Pattern.compile("(\\d+ms)(\\s+)(TTL=\\d+)", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
return 1;
}
return 0;
}
public static void main(String[] args) throws Exception {
// String ipAddress = "10.168.5.218";
// System.out.println(ping(ipAddress, 5, 5000));
List<String> me = new ArrayList();
me.add("asdfsd");
me.get(1);
}
}
這是原創的連結: https://blog.csdn.net/whh743/article/details/54407177