浅谈Executor框架在爬虫中的应用

最近学习了Executor,做一些必要的笔记,一来是对自己学习的知识的巩固,二来对有同样问题的人有参考作用



一 Executor简介

   Java Executor框架是Jdk1.5之后推出的,是为了更加方便的开发多线程应用而封装的框架;
   相比传统的Thread类,Java Executor使用方便,性能更好,更易于管理,而且支持线程池,所以我们在开发爬虫的时候,为了提高爬虫的爬取效率,我们要使用多线程,推荐使用Java的Executor框架来实现,因为Executor框架 既简单又高效;

二 Executor在爬虫中的使用

   常用接口:

  1. 创建固定数目线程的线程池。

    public static ExecutorService newFixedThreadPool(int nThreads) 
    
  2. 执行一个线程

    void java.util.concurrent.Executor.execute(Runnable command)
    
  3. 查看活动线程个数

    int java.util.concurrent.ThreadPoolExecutor.getActiveCount()
    
  4. 结束所有线程

    void java.util.concurrent.ExecutorService.shutdown()
    

   说明:Executor在管理多个线程的时候,会进行有效的安排处理,比如创建的时候,线程池是10个,假如实际线程超过10个,Executor会进行有效的队列阻塞和调度。对我们开发者这是透明的,完全不用关心它内部的具体执行。

三 模拟爬取网页举例

   完整代码:

/**
 * @author ys
 * @version 2.0
 * @date 2020/5/24 18:05
 * @desc: Executor多线程框架 模拟爬取网页
 */
public class ExecutorTest {
    
    private static Integer pages = 1; // 网页数
    private static boolean exeFlag = true; // 执行标识

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10); // 创建ExecutorService线程池 默认连接10个
        
        while(exeFlag){
            if (pages <= 100){
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("爬取了第"+pages+"网页...");
                        ++pages;
                    }
                });
            }else{
                if (((ThreadPoolExecutor)executorService).getActiveCount() == 0){ // 活动线程个数是0
                    executorService.shutdown(); // 结束所有线程
                    exeFlag = false;
                    System.out.println("爬虫任务已经完成");
                }
            }

            try {
                Thread.sleep(100); // 线程休息0.1秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
}

四 总结

   如有错误恳请指正,如有侵权请联系我删除

猜你喜欢

转载自blog.csdn.net/qq_39007083/article/details/106318683
今日推荐