此文已由作者赵计刚授权网易云社区发布。
欢迎访问网易云社区,了解更多网易技术产品运营经验。
前边两章介绍了基础线程池ThreadPoolExecutor的使用方式、工作机理、参数详细介绍以及核心源码解析。
具体的介绍请参照:
第十二章 ThreadPoolExecutor使用与工作机理
1、Executors与ThreadPoolExecutor
使用方法:
package com.collection.test; import java.util.concurrent.Executor; import java.util.concurrent.Executors; public class ThreadPoolExecutorTest { //private static ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10)); //private static Executor executor = Executors.newFixedThreadPool(5); //private static Executor executor = Executors.newSingleThreadExecutor(); //private static Executor executor = Executors.newCachedThreadPool(); private static Executor executor = Executors.newScheduledThreadPool(5); public void executeTask(){ Task1 task1 = new Task1();//构建任务1 Task2 task2 = new Task2();//构建任务2 executor.execute(task1);//执行任务1 executor.execute(task2);//执行任务2 } /* * 基本任务2 */ class Task1 implements Runnable{ public void run() { //具体任务的业务 for(int i=0;i<1000;i++){ System.out.println("hello xxx!!!"); } } } /* * 基本任务2 */ class Task2 implements Runnable{ public void run() { //具体任务的业务 for(int i=0;i<5;i++){ System.out.println("hello world2!!!"); } } } public static void main(String[] args) { ThreadPoolExecutorTest test = new ThreadPoolExecutorTest(); test.executeTask(); } }
2、Executors可以创建的几种线程池简介
注意:对于定时任务的执行,在实际使用中,会去使用spring定时器,非常方便
免费领取验证码、内容安全、短信发送、直播点播体验包及云服务器等套餐
更多网易技术、产品、运营经验分享请点击。