Hutool工具包:使用ThreadUtil创建并使用线程池的简单案例_编程基础

需求:

模拟一个含有100个元素的集合,同时开启5个线程进行遍历。

代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

package com.provy.jiagou;

import cn.hutool.core.thread.ThreadUtil;

import cn.hutool.db.Db;

import cn.hutool.db.Entity;

import java.sql.SQLException;

import java.util.List;

import java.util.concurrent.ExecutorService;

/**

* @author 架构师小跟班

* @Description: https://www.jiagou1216.com

* @date 2020/7/7 18:22

*/

public class Test {

/**

* 初始化线程池,同时执行5个线程

*/

private static ExecutorService executor = ThreadUtil.newExecutor(`5`);

public static void main(String[] args) {

for (`int i = 0; i < 100; i++) {`

//执行线程(jdk1.8版本以上写法)

executor.execute(() -> handler());

}

executor.shutdown();

}

public static void handler() {

//打印当前线程名字

System.out.println(`"当前执行线程:" + Thread.currentThread().getName());`

}

}

打印:

当前执行线程:pool-1-thread-1

当前执行线程:pool-1-thread-5

当前执行线程:pool-1-thread-4

当前执行线程:pool-1-thread-3

当前执行线程:pool-1-thread-3

当前执行线程:pool-1-thread-3

当前执行线程:pool-1-thread-3

当前执行线程:pool-1-thread-2

当前执行线程:pool-1-thread-2

当前执行线程:pool-1-thread-3

当前执行线程:pool-1-thread-3

当前执行线程:pool-1-thread-4

当前执行线程:pool-1-thread-5

当前执行线程:pool-1-thread-5

当前执行线程:pool-1-thread-1

当前执行线程:pool-1-thread-5

当前执行线程:pool-1-thread-5

当前执行线程:pool-1-thread-5

当前执行线程:pool-1-thread-4

当前执行线程:pool-1-thread-3

当前执行线程:pool-1-thread-2

当前执行线程:pool-1-thread-3

当前执行线程:pool-1-thread-4

当前执行线程:pool-1-thread-4

当前执行线程:pool-1-thread-5

当前执行线程:pool-1-thread-5

当前执行线程:pool-1-thread-1

当前执行线程:pool-1-thread-5

当前执行线程:pool-1-thread-5

……


Original url: Access
Created at: 2020-08-14 13:56:20
Category: default
Tags: none

请先后发表评论
  • 最新评论
  • 总共0条评论