import java.net.*; import java.io.*; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.*; public class Main { public static void main(String[] args) { PingTester tester = new PingTester(); tester.startPing(); } } class PingTester { private Queue<String> allIp; private int fetchedNum = 0; // 已经取得的任务数量,每次从队列中取一个ip就加1 public PingTester() { // 首先创建一个队列用于存储所有ip地址 allIp = new LinkedList<String>(); for (int i = 0; i < 10; i++) { //allIp.offer("192.168.9." + i); for (int j = 0; j < 256; j++) { allIp.offer("192.168."+i+"."+j); } } } public void startPing() { // 创建一个线程池,多个线程同时跑 int threadNum = 1000; ExecutorService executor = Executors.newFixedThreadPool(threadNum); for (int i = 0; i < threadNum; i++) { executor.execute(new PingRunner()); } executor.shutdown(); try { while (!executor.isTerminated()) { Thread.sleep(100); } } catch (Exception e) { e.printStackTrace(); } System.out.println("Fetched num is "+fetchedNum); } private class PingRunner implements Runnable { private String taskIp = null; @Override public void run() { try { while ((taskIp = getIp()) != null) { InetAddress addr = InetAddress.getByName(taskIp); if (addr.isReachable(5000)) { System.out.println("host ["+taskIp+"] is reachable"); } else { System.out.println("host ["+taskIp+"] is not reachable"); } } } catch (SocketException e) { System.out.println("host ["+taskIp+"] permission denied"); } catch (Exception e) { System.out.println("---------------------------------------------"+taskIp); e.printStackTrace(); } } public String getIp() { String ip = null; synchronized (allIp) { ip = allIp.poll(); } if (ip != null) { fetchedNum++; } return ip; } } }
用Java实现的多线程扫描IP程序
最新推荐文章于 2024-09-27 13:28:07 发布