標籤:his 速度 exce imp pre mina 結束 todo blog
---恢複內容開始---
檢測本機正在使用的服務連接埠,盡量快完成,計算消耗時間:
輪詢:
1 public class test implements Runnable { 2 //private static String host="210.39.3.164"; 3 private static int i=0; 4 static Date one,two; 5 public synchronized int get(){ 6 if(i>=1024)notifyAll(); 7 return i++; 8 } 9 10 public static void main(String argv[]){11 one=new Date();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(new test()));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 void run(){28 int temp;29 while((temp=get())<1024){30 try { 31 Socket s=new Socket(InetAddress.getLocalHost(),temp);32 System.out.println("服務連接埠: "+temp);33 s.close();34 } catch (UnknownHostException e) {35 // TODO Auto-generated catch block36 e.printStackTrace();37 } catch(ConnectException e){38 System.out.println(temp+"不是服務連接埠");39 }catch (IOException e) {40 // TODO Auto-generated catch block41 e.printStackTrace();42 }43 if(temp==1023){44 two=new Date();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 blocke.printStackTrace();} catch(ConnectException e){//System.out.println(i+"不是服務連接埠");}catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
輪詢方法使用了線程同步,但是沒有多開線程方法速度快
---恢複內容結束---
java 檢測可用連接埠