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

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

轮询:

 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 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=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 block
			e.printStackTrace();
		} catch(ConnectException e){
			//System.out.println(i+"不是服务端口");
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

  

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

 

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