系统预约了几个线程池,不过建议手动建立,以防止错误建立消耗资源,好比建立太多线程或者OOM多线程
建立一个固定长度的线程池,每提交一个任务时就建立一个线程,知道达到线程池的最大数量。无界队列ide
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
单线程的Executor,固定线程数量,数量为1,无界队列,会按顺序执行spa
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
不限制线程数量,使用SynchronousQueue队列,使用于短任务。任务增长时,建立新的线程,线程的数量不受限制。线程池的规模超过当前的处理请求,回收空闲的线程。线程
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
基于ForkJoinPoolcode
public static ExecutorService newWorkStealingPool(int parallelism) { return new ForkJoinPool (parallelism, ForkJoinPool.defaultForkJoinWorkerThreadFactory, null, true); }
用于周期性执行任务orm
public static ScheduledExecutorService newSingleThreadScheduledExecutor() { return new DelegatedScheduledExecutorService (new ScheduledThreadPoolExecutor(1)); }
public class ScheduledDemo { static class Thread1 implements Runnable { @Override public void run() { SimpleDateFormat formater = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); System.out.println(Thread.currentThread().getName() + ":" + formater.format(new Date())); } } public static void main(String[] args) { ScheduledThreadPoolExecutor schedule = new ScheduledThreadPoolExecutor(1); //第一个是Runnable,第二个是第一次开始的时间,第三个是周期时间,第四个是时间单位 schedule.scheduleAtFixedRate(new Thread1(),1000,1000, TimeUnit.MILLISECONDS); } }
运行结果以下:blog