一、newSingleThreadExecutor(单线程线程池)
线程池中只有一个工作线程在处理任务。
1.示例
public static void main(String[] args) { ExecutorService service = Executors.newSingleThreadExecutor(); service.execute(() -> { for (int i = 0; i < 5; i++){ System.out.println("MyJob " + i); } }); for (int i = 0; i < 5; i++) { System.out.println("main "+i); } service.shutdown(); }
2.构建
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
3.特点
核心线程数一个,最大线程数一个,生存时间的0,单位是毫秒 ,使用的任务队列是LinkedBlockingQueue。无核心线程。
4.应用场景
不适合并发,可能会引起I/O阻塞,影响线程相应的操作。
如果业务涉及到顺序消费,可以采用newSingleThreadExecutor
二、newCachedThreadPool(可缓存线程池)
任务只要提交到当前的newCachedThreadPool中,就必然有工作线程可以处理
实例代码:
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 1; i <= 200; i++) {
final int j = i;
executorService.execute(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + j);
});
}
}
构建:
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
特点:
无核心线程,最大线程数为Integer.MAX_VALUE,生存时间为60s,任务队列为:SynchronousQueue
应用场景:
用于执行量大,耗时少的任务。
三、newFixedThreadPool(定长线程池)
构建好当前线程池后,线程个数已经固定好(线程是懒加载,在构建之初,线程并没有构建出来,而是随着人任务的提交才会将线程在线程池中国构建出来)
ExecutorService threadPool = Executors.newFixedThreadPool(3);
threadPool.execute(() -> {
System.out.println("1号任务:" + Thread.currentThread().getName() + System.currentTimeMillis());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
threadPool.execute(() -> {
System.out.println("2号任务:" + Thread.currentThread().getName() + System.currentTimeMillis());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
threadPool.execute(() -> {
System.out.println("3号任务:" + Thread.currentThread().getName() + System.currentTimeMillis());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
构建
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
特点
创建固定大小的核心线程,无非核心线程,执行完立即回收,生存时间为0,任务队列为LinkedBlockingQueue
应用场景
控制线程的最大并发数