线程池管理的工具类,封装类

一、 为什么要使用线程池:
1.频繁创建和销毁线程耗资源,耗时间,换句话说,线程池就能节约资源,节约时间。
2.有的线程执行任务的时间甚至比创建和销毁线程的时间还短。
二 、线程池的作用:
线程池是预先创建线程的一种技术。线程池在还没有任务到来之前,创建一定数量的线程,加入空闲队列中,然后对这些资源进行复用,减少频繁的创建和销毁对象。

线程池涉及的类:
1.Excutor--java里面线程池的接口
2.ExcutorService--真正的线程池接口
3.ScheduledExecutorService(接口)--和Timer/TimerTask类似,解决那些需要重复执行的任务.
4.ThreadPoolExcutor(重点)--ExecutorService的默认实现.
5.ScheduledThreadPoolExecutor(实现类)--继承ThreadPoolExecutor,实现ScheduledExecutorService接口--周期性任务调度的实现.

Executors:
JDK1.5之后的一个新类,提供了一些静态工厂,生成一些常用的线程池.ThreadPoolExecutor类的底层实现.

1.SingleThreadExecutor(单线程)
用法:

ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
singleThreadExecutor.execute(runnable对象);
public static ExecutorService newSingleThreadExecutor() {   
      return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 
                    0L, TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<Runnable>()));
}

创建一个单线程的线程池.这个线程池只有一个线程在工程,也就是相当于单线程串行执行所有任务.如果这个唯一的线程因为异常结束,那么会有一个新的线程来替代它.此线程池保证所有任务的执行顺序都会按照提交的顺序执行.

** 2.FixedThreadPool(固定线程)**
用法:

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(num);
fixedThreadPool.execute(runnable对象);
public static ExecutorService newFixedThreadPool(int nThreads) { 
    return new ThreadPoolExecutor(nThreads, nThreads, 
                          0L, TimeUnit.MILLISECONDS,     
                          new LinkedBlockingQueue<Runnable>());
}

创建固定大小的线程池.每次提交一个任务就会创建一个线程,直到线程达到线程池的最大大小.线程池的大小一旦达到最大值就会保持不变,如果某个线程因为异常而技术,那么该线程池会补充一个新的线程.

3.CachedThreadPool(带缓存)
用法:

ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
cachedThreadPool.execute(runnable对象);
public static ExecutorService newCachedThreadPool() { 
       return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                          60L, TimeUnit.SECONDS, 
                          new SynchronousQueue<Runnable>());
}

创建一个可缓存的线程池.如果线程池的大小超过了处理任务所需要的线程,那么就会回收部分空闲(60秒不执行任务)的线程,当任务数增加时,此线程池又可以智能的添加新线程来处理任务.此线程池不会对线程池大小做限制,线程池大小完全依赖与操作系统(或者说JVM)能够创建的最大线程数.

4.ScheduledThreadPool(定时执行)
用法:

ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(int corePoolSize);
scheduledThreadPool.schedule(runnable对象, 2000, TimeUnit.MILLISECONDS);
public ScheduledThreadPoolExecutor(int corePoolSize) { 
     super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue());
}

创建一个大小无限的线程池.此线程池支持定时以及周期性执行任务的需求.


线程池管理的工具类,封装类。
通过ThreadPoolExecutor的代理类来对线程池的管理实例

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池管理的工具类,封装类
 * @author ThinkPad
 * 线程池的管理 ,通过java 中的api实现管理
 *   采用conncurrent框架: 非常成熟的并发框架 ,特别在匿名线程管理非常优秀的
 *
 */
public class ThreadManager {
    //通过ThreadPoolExecutor的代理类来对线程池的管理
    private static ThreadPollProxy mThreadPollProxy;
    //单列对象
    public static ThreadPollProxy getThreadPollProxy(){
        synchronized (ThreadPollProxy.class) {
            if(mThreadPollProxy==null){
                mThreadPollProxy=new ThreadPollProxy(3,6,1000); 
            }
        }
        return mThreadPollProxy;
    }
    //通过ThreadPoolExecutor的代理类来对线程池的管理
    public static class ThreadPollProxy{
        private ThreadPoolExecutor poolExecutor;//线程池执行者 ,java内部通过该api实现对线程池管理
        private int corePoolSize;
        private int maximumPoolSize;
        private long keepAliveTime;
        
        public ThreadPollProxy(int corePoolSize,int maximumPoolSize,long keepAliveTime){
            this.corePoolSize=corePoolSize;
            this.maximumPoolSize=maximumPoolSize;
            this.keepAliveTime=keepAliveTime;
        }
        //对外提供一个执行任务的方法
        public void execute(Runnable r){
            if(poolExecutor==null||poolExecutor.isShutdown()){
                poolExecutor=new ThreadPoolExecutor(
                        //核心线程数量
                        corePoolSize, 
                        //最大线程数量
                        maximumPoolSize, 
                        //当线程空闲时,保持活跃的时间
                        keepAliveTime,
                        //时间单元 ,毫秒级
                        TimeUnit.MILLISECONDS, 
                        //线程任务队列 
                        new LinkedBlockingQueue<Runnable>(), 
                        //创建线程的工厂
                        Executors.defaultThreadFactory());
            }
            poolExecutor.execute(r);    
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容