java 多线程主机Ip扫描

葫芦的运维日志

下一篇 搜索 上一篇

浏览量 4346

2014/04/07 16:32


1、创建集合用来存所有的ip地址,并指定实现类。
        private Queue<String> allIp;
        allIp = new LinkedList <String>();
        for (int i = mini ; i <= maxi; i++) {
                     String host = hosts + "." + i;
                      allIp.offer( host);
              }
2、创建runnable实现类,创建 getIp()方法每次取一个ip地址测试,synchronized 用以同步处理。
private class rHost implements Runnable {
               private String taskIp = null;
              Message msg = new Message();
               private LinkedList link = new LinkedList();
               @Override
               public void run() {

                      try {
                            while ((taskIp = getIp()) != null) {
                                   if (flag == 1) {
                                         InetAddress addr = InetAddress.getByName(taskIp);
                                          status = (( s - mini) * 100 / ( maxi - mini));
                                          if (addr.isReachable(gettimeout())) {
                      count++;

                                                 link.add(taskIp);
                                         }
                                          handler1.sendEmptyMessage( status);

                                  } else if (flag == 2) {
                                         Thread. currentThread().interrupt();
                                  }

                           }
                            if (!link .isEmpty()) {
                                   msg. obj = link;
                                   pingHandler.sendMessage(msg );
                           }
                     } catch (Exception e) {
                           e.printStackTrace();
                     }

              }
               public String getIp() {
                     String ip = null;

                      synchronized (allIp ) {
                           ip = allIp.poll();
                            s++;
//                         System.out.println(s);
                     }
                      return ip;
              }

3、创建线程池添加上面的runnable接口。
        public void startPing() {
               count = 0;
               int threadNum = 100;
              ExecutorService executor = Executors. newFixedThreadPool(threadNum);
               for (int i = 0; i < threadNum; i++) {
                     executor. execute(new rHost());
              }
              executor.shutdown();
               try {
                      while (!executor.isTerminated()) {
                           Thread. sleep(100);

                     }
              } catch (Exception e) {
                     e.printStackTrace();
              }
       }

 

葫芦的运维日志

打赏

上一篇 搜索 下一篇
© 冰糖葫芦甜(bthlt.com) 2021 王梓打赏联系方式 陕ICP备17005322号-1