java自带线程池Executors

Executors类里边常用的四种线程池

public class Executors {

//1.newFixedThreadPool

创建一个定长线程池,可控制线程最大并发数,超出的线程会在无界队列中等待

public static ExecutorService newFixedThreadPool(int nThreads) {

return new ThreadPoolExecutor(nThreads, nThreads,

0L, TimeUnit.MILLISECONDS,

new LinkedBlockingQueue<Runnable>());

}

//2.newSinglethreadExecutor

创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有的任务按照指定的顺序(FIFO,LIFO,优先级)执行

public static ExecutorService newSingleThreadExecutor() {

return new FinalizableDelegatedExecutorService

(new ThreadPoolExecutor(1, 1,

0L, TimeUnit.MILLISECONDS,

new LinkedBlockingQueue<Runnable>()));

}

//3.newCachedThreadPool

创建一个可缓存线程池,如果线程池超过处理需要,可灵活回收空闲线程,若无回收线程,则新建线程

public static ExecutorService newCachedThreadPool() {

return new ThreadPoolExecutor(0, Integer.MAX_VALUE,

60L, TimeUnit.SECONDS,

new SynchronousQueue<Runnable>());

}

public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {

return new ThreadPoolExecutor(0, Integer.MAX_VALUE,

60L, TimeUnit.SECONDS,

new SynchronousQueue<Runnable>(),

threadFactory);

}

//4.newScheduledThreadPool

创建一个定长线程池,支持定时及周期性任务执行

    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {

        return new ScheduledThreadPoolExecutor(corePoolSize);

    }

}

//四种线程池其实内部方法都是调用的ThreadPoolExecutor类,只不过利用了其不同的构造方法而已(传入自己需要传入的参数),那么利用这个特性,我们自己也是可以实现自己定义的线程池

}

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