java中ThreadPoolExecutor线程池的使用

来源:互联网 发布:进口商品条码查询软件 编辑:程序博客网 时间:2024/05/16 01:04
1.线程池类:Java.util.concurrent.ThreadPoolExecutor.常用的构造方法:

ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,long keepAliveTime, TimeUnit unit,BlockingQueue<Runnable> workQueue,RejectedExecutionHandler handler);

参数说明:

    corePoolSize: 线程池维护线程的最少数量

    maximumPoolSize:线程池维护线程的最大数量

    keepAliveTime: 线程池维护线程所允许的空闲时间

    unit: 线程池维护线程所允许的空闲时间的单位

    workQueue: 线程池所使用的缓冲队列

    handler: 线程池对拒绝任务的处理策略(可空,为空时当接收到超出缓冲队列的任务时,会抛出异常)

一个任务通过 execute(Runnable)方法被添加到线程池,任务就是一个 Runnable类型的对象,任务的执行方法就是Runnable类型对象的run()方法。当一个任务通过execute(Runnable)方法欲添加到线程池时:
   a.如果此时线程池中的数量小于corePoolSize,即使线程池中的线程都处于空闲状态,也要创建新的线程来处理被添加的任务。
        测试程序如下:
            ThreadPoolExecutor tp = new ThreadPoolExecutor(100, 100, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(count),new ThreadPoolExecutor.DiscardOldestPolicy());
            for( int i = 0 ; i < count ; i ++){
            final int s = i;
            tp.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } //暂停1秒
                    System.out.println("当前线程ID:" + Thread.currentThread().getId());
                }
            });
        }
        此时的输出:
            当前线程ID:9
            当前线程ID:17
            当前线程ID:15
            当前线程ID:16
            当前线程ID:14
            当前线程ID:13
            当前线程ID:12
            当前线程ID:10
            当前线程ID:11
            当前线程ID:18
        如果改成 ThreadPoolExecutor tp = new ThreadPoolExecutor(22, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(count),new ThreadPoolExecutor.DiscardOldestPolicy());
         则输出:
            当前线程ID:9
            当前线程ID:10
            当前线程ID:9
            当前线程ID:10
            当前线程ID:9
            当前线程ID:10
            当前线程ID:9
            当前线程ID:10
            当前线程ID:9
            当前线程ID:10
   b.如果此时线程池中的数量等于 corePoolSize,但是缓冲队列 workQueue未满,那么任务被放入缓冲队列。

   c.如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量小于maximumPoolSize,建新的线程来处理被添加的任务。

   d.如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量等于maximumPoolSize,那么通过 handler所指定的策略来处理此任务。也就是:处理任务的优先级为:核心线程corePoolSize、任务队列workQueue、最大线程maximumPoolSize,如果三者都满了,使用handler处理被拒绝的任务。
   f.当线程池中的线程数量大于 corePoolSize时,如果某线程空闲时间超过keepAliveTime,线程将被终止。这样,线程池可以动态的调整池中的线程数。

    

下面给出一个例子,看看使用线程池和不使用线程池的性能差别:

需求:往一个List中添加随机数。(十万量级)

    使用线程池:

public class UseThreadPoolTest {    private static final int count = 100000;    public static void main(String[] args) {        long startTime = System.currentTimeMillis();        final List<Integer> list = new LinkedList<Integer>();        ThreadPoolExecutor tp = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(count),new ThreadPoolExecutor.DiscardOldestPolicy());        final Random random = new Random();        for( int i = 0 ; i < count ; i ++){            tp.execute(new Runnable() {                @Override                public void run() {                    list.add(random.nextInt());                                    }            });        }        tp.shutdown();        try{            tp.awaitTermination(1, TimeUnit.DAYS);        }catch(InterruptedException e){            e.printStackTrace();        }        System.out.println("耗时:{"+(System.currentTimeMillis()-startTime)+"}毫秒");        System.out.println("队列大小:"+list.size());    }}

运行的结果:
    
只是使用多线程:
    
public class NotUseThreadPoolTest {    private static final int count = 100000;    public static void main(String[] args) {        long startTime = System.currentTimeMillis();        final List<Integer> list = new LinkedList<Integer>();        final Random random = new Random();        for (int i = 0 ; i < count;i++){            Thread thread = new Thread(){                @Override                public void run(){                    list.add(random.nextInt());                }            };            thread.start();            try{                thread.join();            }catch(InterruptedException e){                e.printStackTrace();            }        }        System.out.println("耗时:{"+(System.currentTimeMillis() - startTime)+"}毫秒");        System.out.println("队列大小:"+list.size());    }}

运行结果:
    

一般的配置为:

<bean id="threadPoolTaskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"><!-- 核心线程数,默认为1 --><property name="corePoolSize" value="30" /><!-- 最大线程数,默认为Integer.MAX_VALUE --><property name="maxPoolSize" value="80" /><!-- 队列最大长度,一般需要设置值>=notifyScheduledMainExecutor.maxNum;默认为Integer.MAX_VALUE --><property name="queueCapacity" value="1000" /><!-- 线程池维护线程所允许的空闲时间,默认为60s --><property name="keepAliveSeconds" value="300" /><!-- 线程池对拒绝任务(无线程可用)的处理策略,目前只支持AbortPolicy、CallerRunsPolicy;默认为后者 --><property name="rejectedExecutionHandler"><!-- AbortPolicy:直接抛出java.util.concurrent.RejectedExecutionException异常 --><!-- CallerRunsPolicy:主线程直接执行该任务,执行完之后尝试添加下一个任务到线程池中,可以有效降低向线程池内添加任务的速度 --><!-- DiscardOldestPolicy:抛弃旧的任务、暂不支持;会导致被丢弃的任务无法再次被执行 --><!-- DiscardPolicy:抛弃当前任务、暂不支持;会导致被丢弃的任务无法再次被执行 --><bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" /></property></bean>










0 0
原创粉丝点击