系统预定了几个线程池,不过建议手动创建,以防止错误创建消耗资源,比如创建太多线程或者OOM
固定线程数量,无界队列
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
固定线程数量,数量为1,无界队列,会按顺序执行
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>()); }
基于ForkJoinPool
public static ExecutorService newWorkStealingPool(int parallelism) { return new ForkJoinPool (parallelism, ForkJoinPool.defaultForkJoinWorkerThreadFactory, null, true); }
用于周期性执行任务
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); } }
运行结果如下: