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 }