背景
某些业务场景下需要使用多线程并发执行任务,增大吞吐量,这里给出一个多线程并发任务创建与执行的 demo
目录
- 线程池创建
- 并发任务创建
- 任务并发执行
线程池创建
谈到多线程,肯定少不了线程池的创建,这里自定义一个线程池工厂,方便扩展
public class ExecutorFactory {
public static ExecutorService newInstance(){
ExecutorService executor = new ThreadPoolExecutor(
10,
10,
30,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(10));
return executor;
}
}
任务创建
创建并发执行的任务类
public class Task implements Runnable {
private String taskName;
public Task(String taskName) {
this.taskName = taskName;
}
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(taskName);
}
}
测试
测试并发任务执行
public class TaskTest {
public static void main(String[] args) {
testTask();
}
public static void testTask(){
ExecutorService executorService = ExecutorFactory.newInstance();
Task task1 = new Task("task1");
Task task2 = new Task("task2");
Task task3 = new Task("task3");
List<Task> tasks = new ArrayList<>();
tasks.add(task1);
tasks.add(task2);
tasks.add(task3);
System.out.println("start...");
for (Task task : tasks) {
executorService.submit(task);
}
}
}