java测试端口_java 检测可用端口

---恢复内容开始---

检测本机正在使用的服务端口,尽量快完成,计算消耗时间:

轮询:

1 public class test implementsRunnable {2 //private static String host="210.39.3.164";

3 private static int i=0;4 staticDate one,two;5 public synchronized intget(){6 if(i>=1024)notifyAll();7 return i++;8 }9

10 public static voidmain(String argv[]){11 one=newDate();12 //long time=one.getTime()-two.getTime();13 //System.out.println(time);

14 ExecutorService pool = Executors.newFixedThreadPool(30);15 for(int j=0;j<15;j++){16 pool.submit(new Thread(newtest()));17 }18 pool.shutdown();19 while(true){20 if(pool.isTerminated()){21 System.out.println(two.getTime()-one.getTime());22 break;23 }24 }25 }26

27 public voidrun(){28 inttemp;29 while((temp=get())<1024){30 try{31 Socket s=newSocket(InetAddress.getLocalHost(),temp);32 System.out.println("服务端口: "+temp);33 s.close();34 } catch(UnknownHostException e) {35 //TODO Auto-generated catch block

36 e.printStackTrace();37 } catch(ConnectException e){38 System.out.println(temp+"不是服务端口");39 }catch(IOException e) {40 //TODO Auto-generated catch block

41 e.printStackTrace();42 }43 if(temp==1023){44 two=newDate();45 }46 }47 }48 }

尽量多开线程:

public class test {

public static void main(String argv[]){

int i;

Date d=new Date();

ExecutorService pool = Executors.newFixedThreadPool(1204);

for(i=1;i<=1024;i++){

pool.submit(new Thread(new thread(i)));

}

pool.shutdown();

while(true){

if(pool.isTerminated()){

Date last=new Date();

System.out.println(last.getTime()-d.getTime());

break;

}

}

}

}

class thread implements Runnable{

int i;

thread(int i){

this.i=i;

}

public void run(){

try {

Socket s=new Socket(InetAddress.getLocalHost(),i);

System.out.println("服务端口: "+i);

s.close();

} catch (UnknownHostException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch(ConnectException e){

//System.out.println(i+"不是服务端口");

}catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

轮询方法使用了线程同步,但是没有多开线程方法速度快

---恢复内容结束---

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值