SpringBoot 线程池(一):使用同步线程池
1 创建任务
1.1 创建同步任务类 SyncTask
创建同步任务类 SyncTask
,添加 @Component
注释
1.2 创建需要执行的任务
为了测试方便,只打印一行信息
/**
* 同步任务
*/
public void sync() {
try {
System.out.println(Thread.currentThread().getName() + ":sync execute task...");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
1.3 创建线程池、任务执行调用方法
/** 同步任务线程池 */
private final ExecutorService executorService = new ThreadPoolExecutor(10, 20, 60L,
TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(50),
new ThreadFactoryBuilder().setNameFormat("sync-task-thread-pool-%d").build());
/**
* 执行方法
*/
public void execute() {
// 提交任务给线程池
executorService.submit(this::sync);
}
1.4 SyncTask 类完整代码
@Component
public class SyncTask {
/** 同步任务线程池 */
private final ExecutorService executorService = new ThreadPoolExecutor(10, 20, 60L,
TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(50),
new ThreadFactoryBuilder().setNameFormat("sync-task-thread-pool-%d").build());
/**
* 同步任务
*/
public void sync() {
try {
System.out.println(Thread.currentThread().getName() + ":sync execute task...");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 执行方法
*/
public void execute() {
// 提交任务给线程池
executorService.submit(this::sync);
}
}
2 创建单元测试进行测试
本次使用 JUnit5
进行测试,完整代码如下:
2.1 不使用线程池
@SpringBootTest
class StudyApplicationTests {
@Autowired
SyncTask syncTask;
@Test
public void syncWithoutThreadPool() {
System.out.println("start execute task...");
long startTime = System.currentTimeMillis();
for (int i = 0; i < 10 ; i++) {
syncTask.sync();
}
long endTime = System.currentTimeMillis();
System.out.println("total time:" + (endTime - startTime));
}
}
打印日志结果:
start execute task...
main:sync execute task...
main:sync execute task...
main:sync execute task...
main:sync execute task...
main:sync execute task...
main:sync execute task...
main:sync execute task...
main:sync execute task...
main:sync execute task...
main:sync execute task...
total time:10117
2.2 使用线程池
@SpringBootTest
class StudyApplicationTests {
@Autowired
SyncTask syncTask;
@Test
public void syncWithThreadPool() {
System.out.println("start execute task...");
long startTime = System.currentTimeMillis();
for (int i = 0; i < 10 ; i++) {
syncTask.execute();
}
long endTime = System.currentTimeMillis();
System.out.println("total time:" + (endTime - startTime));
}
}
打印日志结果:
start execute task...
sync-task-thread-pool-0:sync execute task...
sync-task-thread-pool-1:sync execute task...
sync-task-thread-pool-2:sync execute task...
sync-task-thread-pool-3:sync execute task...
sync-task-thread-pool-4:sync execute task...
sync-task-thread-pool-5:sync execute task...
sync-task-thread-pool-6:sync execute task...
sync-task-thread-pool-7:sync execute task...
sync-task-thread-pool-8:sync execute task...
total time:2
sync-task-thread-pool-9:sync execute task...
3 总结
由上述结果可见:使用线程池执行批量任务速度要快。