java线程池创建与调用

public class ExcutorUtil {

    static ExecutorService fixedThreadPool = null;
    //线程池大小,可自己定义
    static final Integer nThreads = 100;

    static {
        if (fixedThreadPool == null) {
            fixedThreadPool = new ThreadPoolExecutor(nThreads, nThreads,
                    0L, TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<Runnable>());
        }
    }

    public static void execute(Thread thread) {
        fixedThreadPool.execute(thread);
    }

    public static Future<?> submit(Callable<?> c) {
        return (Future<?>) fixedThreadPool.submit(c);
    }

    public static void execute(Runnable runnable) {
        fixedThreadPool.execute(runnable);
    }
}
  • 创建源码为:
 public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }
  •  参数解析
序号 名称 类型 含义
1 corePoolSize int 核心线程池大小
2 maximumPoolSize int 最大线程池大小
3 keepAliveTime long 线程最大空闲时间
4 unit TimeUnit 时间单位
5 workQueue BlockingQueue<Runnable> 线程等待队列
6 threadFactory ThreadFactory 线程创建工厂
7 handler RejectedExecutionHandler 拒绝策略

 

  • 以下代码为调用代码
     ExcutorUtil.execute(()->{
            //do something
       });

 

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