java线程池
Java里面提供有四种线程池,分别是定时任务线程池,固定线程数的线程池,不限线程数的线程池,单线程的线程池。
1.定时任务线程池
能够用于执行循环的任务,还可以延迟执行任务,具体代码如下所示
/** * 执行定期任务 * 执行延期任务 */ public class ScheduledThreadPool { private static ScheduledThreadPool instance = new ScheduledThreadPool(); private ScheduledExecutorService scheduledThreadPool; private Map<String, Future> futureMap = new HashMap<>(); private int scheduledPoolSize = 5;//线程池大小 private ScheduledThreadPool(){ scheduledThreadPool = Executors.newScheduledThreadPool(scheduledPoolSize); } public static ScheduledThreadPool getInstance(){ return instance; } public void execute(Runnable runnable,int period,String tag){ Future future = this.scheduledThreadPool.scheduleAtFixedRate(runnable, 0, period, TimeUnit.MILLISECONDS); futureMap.put(tag, future); } public void executeDelay(Runnable runnable,int delay){ this.scheduledThreadPool.schedule(runnable, delay, TimeUnit.MILLISECONDS); } public void stopTask(String tag){ Future future = this.futureMap.get(tag); if(future != null){ future.cancel(true); futureMap.remove(tag); } } }
2.固定线程数的线程池
线程池的线程数量固定,如果需要执行的线程数超过了固定的大小,则超出的任务等待现有的任务执行完之后才能执行。
/** *固定线程池,固定大小 */ public class FixedThreadPool { private static FixedThreadPool instance = new FixedThreadPool(); private ExecutorService fixedThreadPool; private int fixedPoolSize = 3;//线程池大小 private FixedThreadPool(){ fixedThreadPool = Executors.newFixedThreadPool(fixedPoolSize); } public static FixedThreadPool getInstance(){ return instance; } public void execute(Runnable runnable){ fixedThreadPool.execute(runnable); } }
3.不限线程数的线程池
线程池可以无限大,由Java自动管理,任务完成后回收线程。
/** * 线程池无限大 * 可复用之前使用的线程 * 自动回收线程 */ public class LimitlessThreadPool { private static LimitlessThreadPool instance = new LimitlessThreadPool(); private ExecutorService cachedThreadPool; private LimitlessThreadPool(){ cachedThreadPool = Executors.newCachedThreadPool(); } public static LimitlessThreadPool getInstance(){ return instance; } public void execute(Runnable runnable){ this.cachedThreadPool.execute(runnable); } }
4.单线程的线程池
线程池当中只有一个线程,等一个任务完成之后才能继续进行下一个,按照先进先出的顺序。
/** * 单线程池,按照先进先出顺序执行 * 线程池中只有一个线程 */ public class SingleThreadExecutor { private static SingleThreadExecutor instance = new SingleThreadExecutor(); private ExecutorService singleThreadExecutor; private SingleThreadExecutor(){ singleThreadExecutor = Executors.newSingleThreadExecutor(); } public static SingleThreadExecutor getInstance(){ return instance; } public void execute(Runnable runnable){ this.singleThreadExecutor.execute(runnable); } }