Java Executor框架使用

  Java Executor框架是Jdk1.5之后推出的,是为了更加方便的开发多线程应用而封装的框架;

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

Java Executor框架在爬虫应用中的使用

  常用接口:

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

  public static ExecutorService newFixedThreadPool(int nThreads) 

   

  执行一个线程

  void java.util.concurrent.Executor.execute(Runnable command)

  查看活动线程个数

  int java.util.concurrent.ThreadPoolExecutor.getActiveCount()

  结束所有线程

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

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

  测试用例

  

 1 import java.util.concurrent.ExecutorService;
 2 import java.util.concurrent.Executors;
 3 import java.util.concurrent.ThreadPoolExecutor;
 4 import java.util.concurrent.atomic.AtomicInteger;
 5 
 6 /**
 7  * @author zsh
 8  * @site www.qqzsh.top
 9  * @company wlgzs
10  * @create 2019-06-02 10:57
11  * @description
12  */
13 public class ExecutorTest {
14 
15     // 执行标识
16     private static boolean exeFlag=true;
17 
18     public static void main(String[] args) throws InterruptedException {
19         // 创建ExecutorService 连接池创建固定的10个初始线程
20         ExecutorService executorService = Executors.newFixedThreadPool(2);
21         AtomicInteger atomicInteger = new AtomicInteger();
22 
23         while (exeFlag){
24             if (atomicInteger.get() <= 100){
25                 executorService.execute(new Runnable() {
26                     @Override
27                     public void run() {
28                         System.out.println("爬取了第"+atomicInteger.get()+"网页...");
29                         atomicInteger.getAndIncrement();
30                     }
31                 });
32             }else {
33                 if (((ThreadPoolExecutor)executorService).getActiveCount() == 0){
34                     executorService.shutdown();
35                     exeFlag=false;
36                     System.out.println("爬虫任务已经完成");
37                 }
38             }
39 
40            Thread.sleep((long) 0.1);
41         }
42     }
43 }

猜你喜欢

转载自www.cnblogs.com/zsh-blogs/p/10963106.html