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);
        }
    }
}

 

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