多線程判斷本網段有多少可以ping通的ip

  • ping命令空格問題,正確如下:
Process p = Runtime.getRuntime().exec("ping -n 1 "+ip);//空格引發的災難
  • 線程池關閉方式有誤,只使用了threadPool.shutdown()進行關閉,正確如下:
// 等待所有線程結束的時候,就關閉線程池
        threadPool.shutdown();
        System.out.println("終於找完了,可以ping通ip如下:");
      //等待線程池關閉,但是最多等待1個小時
        if (threadPool.awaitTermination(1, TimeUnit.HOURS)) {
        for (String theip : slist) {
            System.out.println(theip);
        	}
        }

該圖片來自於https://blog.csdn.net/weixin_43207056/article/details/103566392
在這裏插入圖片描述
完整實現如下:

package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestIp {
	
	public static void main(String[] args) throws IOException,InterruptedException {
		// 創建線程池
		ThreadPoolExecutor threadPool= new ThreadPoolExecutor(200, 200, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
		//保證List線程安全
		 List<String> slist = Collections.synchronizedList(new ArrayList<>());
		for(int i = 0; i<255; i++) {
			String s = "192.168.1."+i;
	        threadPool.execute(new Runnable(){
	            public void run() {
					if(isPing(s)) 
						slist.add(s);
	            }
	               
	        }); 
		}
		
		// 等待所有線程結束的時候,就關閉線程池
        threadPool.shutdown();
        System.out.println("終於找完了,可以ping通ip如下:");
      //等待線程池關閉,但是最多等待1個小時
        if (threadPool.awaitTermination(1, TimeUnit.HOURS)) {
        for (String theip : slist) {
            System.out.println(theip);
        	}
        }
	}	
	
	//判斷一個ip是否能夠ping通
	private static boolean isPing(String ip){
	
		try {
		boolean reachable =false;
		StringBuilder sb = new StringBuilder();
		Process p = Runtime.getRuntime().exec("ping -n 1 "+ip);//空格引發的災難
		BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
		String line = null;
			while((line=br.readLine()) != null) {
				if(line.length() != 0) 
					sb.append(line+"\r\n");
			}
		reachable = sb.toString().contains("TTL");
		br.close();
		return reachable;
		}catch(IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
	}
	
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章