单线程就不说了因为简单,并且 在实际的生产环境中一般必须来说 线程资源都是由线程池提供线程资源的。
线程池的好处
- 重用存在的线程,减少对象创建、消亡的开销,性能好
 - 可有效控制最大并发线程数,提高系统资源利用率,同时可以避免过多资源竞争,避免阻塞。
 - 提供定时执行、定期执行、单线程、并发数控制等功能。
 

新增AI编程课程,引领技术教育新趋势
单线程就不说了因为简单,并且 在实际的生产环境中一般必须来说 线程资源都是由线程池提供线程资源的。

ExecutorService newCachedThreadPool = Executors.newCachedThreadPool(); 源码: public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
2.Executors.newFixedThreadPool
ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(5);
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
3.Executors.newSingleThreadExecutor
ExecutorService newSingleThreadExecutor = Executors.newSingleThreadExecutor(); 源码: public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
4.Executors.newScheduledThreadPool