背景
某些業(yè)務(wù)場(chǎng)景下需要使用多線(xiàn)程并發(fā)執(zhí)行任務(wù),增大吞吐量,這里給出一個(gè)多線(xiàn)程并發(fā)任務(wù)創(chuàng)建與執(zhí)行的 demo
目錄
- 線(xiàn)程池創(chuàng)建
- 并發(fā)任務(wù)創(chuàng)建
- 任務(wù)并發(fā)執(zhí)行
線(xiàn)程池創(chuàng)建
談到多線(xiàn)程,肯定少不了線(xiàn)程池的創(chuàng)建,這里自定義一個(gè)線(xiàn)程池工廠,方便擴(kuò)展
public class ExecutorFactory {
public static ExecutorService newInstance(){
ExecutorService executor = new ThreadPoolExecutor(
10,
10,
30,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(10));
return executor;
}
}
任務(wù)創(chuàng)建
創(chuàng)建并發(fā)執(zhí)行的任務(wù)類(lèi)
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);
}
}
測(cè)試
測(cè)試并發(fā)任務(wù)執(zhí)行
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);
}
}
}