Executor多线程框架使用

在我们的JDK1.5的时候JAVA推出一款为了更加方便开发的多线程应用而封装的框架(Executor),相比传统的Thread类,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.concrrent.ExecutorService.shutdonw()

Executor在管理多个线程的时候会进行有效的安排。处理,比如创建的时候线程池里有10个线程,加入实现线程超过10个Executor会进行有效的队列阻塞和调度。对于我们开发者开说这是透明的,完全不需要关心它内部是怎么进行的操作。

实例代码:

package com.java.executor;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class ExecutorTest {
    private static Integer count = 1; //数量
    
    private static boolean flag = true;//是否执行
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);//在连接池中初始化10个线程
        while(flag){
            if(count<=100){
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("执行 : " + count++);
                    }
                });
            }else{
                //判断是否有活动线程
                if(((ThreadPoolExecutor)executorService).getActiveCount()==0){
                    executorService.shutdown();//结束所有线程
                    flag=false;
                    System.out.println("完成操作");
                }
            }
            try {
                Thread.sleep(100);//休息0.1秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

这是Executor简单的使用方式,方便快捷,学习难度底,在这里我们为什么要休息0.1秒呢,在上面这段代码上我们是没有加锁的,如果不休息在这段代码上等count大于100的时候,线程还在活动中会导致线程没有进行关闭,加上线程执行速度的飞快会超过我们需求,并且在爬虫爬网页的时候使用这么块的速度是很容易封IP的。

猜你喜欢

转载自www.cnblogs.com/SimpleWu/p/9709272.html