Java如何实现同时开100个ping?
一定要同时,在网上找了java 实现ping的代码
public class javaping {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("ping 221.120.222.26 -t");
byte[] msg = new byte[128];
int len;
while((len=p.getInputStream().read(msg)) >0) {
System.out.print(new String(msg, 0, len));
}
String rs = "\n";
byte[] rb = new byte[] { (byte)'\n' } ; //rs.getBytes();
OutputStream os = p.getOutputStream();
os.write(rb);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} 但是这个是只ping一次 我想测试的是 在同一秒之内同时ping100次,不能用循环,是不是要通过线程来实现啊?
我对线程也不是很了解,请知道的朋友告诉一下如何实现 谢谢!~
一定要同时,在网上找了java 实现ping的代码
public class javaping {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("ping 221.120.222.26 -t");
byte[] msg = new byte[128];
int len;
while((len=p.getInputStream().read(msg)) >0) {
System.out.print(new String(msg, 0, len));
}
String rs = "\n";
byte[] rb = new byte[] { (byte)'\n' } ; //rs.getBytes();
OutputStream os = p.getOutputStream();
os.write(rb);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} 但是这个是只ping一次 我想测试的是 在同一秒之内同时ping100次,不能用循环,是不是要通过线程来实现啊?
我对线程也不是很了解,请知道的朋友告诉一下如何实现 谢谢!~
import java.lang.Thread;
import java.text.SimpleDateFormat;
import java.util.Date;class MyThread extends Thread {
public void run() {
try {
Process p = Runtime.getRuntime().exec("ping 221.120.222.19");
byte[] msg = new byte[128];
int len;
while((len=p.getInputStream().read(msg)) >0) {
//System.out.print(new String(msg, 0, len));
}
String rs = "\n";
byte[] rb = new byte[] { (byte)'\n' } ; //rs.getBytes();
OutputStream os = p.getOutputStream();
os.write(rb);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}public class Test {
public static void main(String[] args) throws Exception {
SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMMddHHmmss");
String start = tempDate.format(new Date());
System.out.println(" 开始:"+start);
for (int i = 0; i < 100; i++) {
Thread t = new MyThread();
t.start();
}
String end = tempDate.format(new Date());
System.out.println(" 结束:"+end);
}
}这么写对吗?
import java.lang.Thread;
import java.text.SimpleDateFormat;
import java.util.Date;class MyThread extends Thread {
public void run() {
try {
Process p = Runtime.getRuntime().exec("ping 221.120.222.19");
byte[] msg = new byte[128];
int len;
while((len=p.getInputStream().read(msg)) >0) {
//System.out.print(new String(msg, 0, len));
}
String rs = "\n";
byte[] rb = new byte[] { (byte)'\n' } ; //rs.getBytes();
OutputStream os = p.getOutputStream();
os.write(rb);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}public class Test {
public static void main(String[] args) throws Exception {
SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMMddHHmmss");
String start = tempDate.format(new Date());
System.out.println(" 开始:"+start);
for (int i = 0; i < 100; i++) {
Thread t = new MyThread();
t.start();
}
String end = tempDate.format(new Date());
System.out.println(" 结束:"+end);
}
}这么写对吗?