Java线程池

参考ThreadPoolExecutor类讲解

*new Thread的弊端:

1.每次新建对象性能差。

2.线程缺乏统一管理,可能无限制新建线程,相互之间竞争资源,及可能占用过多系统资源导致死机或oom。

3.缺乏更多功能,如定时,定期执行,线程中断。

*相比new Thread,java提供的四种线程池好处在于:

1.重用存在的线程,减少对象创建,消亡的开销,性能佳。

2.可有效控制最大并发线程数,提高系统资源的使用率,同时避免过多资源竞争,避免阻塞。

3.提供定时,定期执行,单线程,并发数控制等功能。

*Java通过Executors提供四种线程池,分别为:

1.newCachedThreadPool->创建一个可缓存的线程池,如果线程池的长度超过处理需要,可灵活回收

   空闲线程,如无可回收,则新建线程。

2.newFixedThreadPool->创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。

3.newScheduledThreadPool->创建一个定长线程池,支持定时及周期性任务执行。

4.newSingleThreadExecutor->创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证

   所有任务按照指定顺序(FIFO,LIFO,优先级)执行。

*实例

public class ThreadPoolTest {
    private static ExecutorService cachedThreadPool=Executors.newCachedThreadPool();
    private static ExecutorService fixedThreadPool=Executors.newFixedThreadPool(5);
    private static ExecutorService singleThread=Executors.newSingleThreadExecutor();
    private static MyThreadPool myThreadPool=new MyThreadPool(5,10);


    public static void main(String[] args) {
        for (int i=0;i<111;i++){
            myThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    getTime();
                }
            });
        }
    }

    public static void getTime(){
        try {
            Thread.sleep(100);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"="+System.currentTimeMillis());
    }

    static class MyThreadPool{
        private ThreadPoolExecutor executor;
        public MyThreadPool(int corePoolSize,int maximumPoolSize){
            /**
             * 参数1:核心线程池大小
             * 参数2:最大线程池大小
             * 参数3:大于corePoolSize的线程在执行完任务后多久被杀死
             * 参数4:keepAliveTime时间单位
             * 参数5:要执行的任务队列
             * 参数6:线程工厂,用于创建线程
             */
            LinkedBlockingQueue<Runnable> workQueue=new LinkedBlockingQueue<>(100);
            executor=new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 60L,
                    TimeUnit.MILLISECONDS, workQueue, new ThreadFactory() {
                private AtomicInteger count=new AtomicInteger(0);
                @Override
                public Thread newThread(@NonNull Runnable runnable) {
                    Thread thread=new Thread(runnable,"Thread-"+count.incrementAndGet());
                    return thread;
                }
            });
        }
        void execute(Runnable var1){
            executor.execute(var1);
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章