- import java.util.concurrent.*;
- /**
- * @Author : YuanXin
- * @create 2024/2/1 11:11
- * @Description :
- */
- public class Main {
- public static void main(String[] args) {
- taskListImpl taskList = new taskListImpl();
- String taskJksj = taskList.poolExecutorJksj();
- String taskJxdx = null;
- if (taskJksj.equals("taskJksjSuccess")) {
- taskJxdx = taskList.poolExecutorJxdx();
- }
- if (taskJxdx.equals("taskJxdxSuccess")) {
- taskList.poolExecutorNbzz();
- }
-
- }
- }
- class taskListImpl {
- // 创建一些任务
- int[] taskJksj = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
- int[] taskJxdx = new int[]{15, 16, 17, 18};
- int[] taskNbzz = new int[]{101, 102};
- public String poolExecutorJksj() {
- ThreadPoolExecutor pool =
- new ThreadPoolExecutor(
- 3,
- 10,
- 3,
- TimeUnit.SECONDS,
- new LinkedBlockingDeque<>(5),
- Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy()
- );
- // ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
- // ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
-
- try {
- for (int i = 0; i < taskJksj.length; i++) {
- int num = i;
- pool.execute(() -> {
- taskJksjPool(num);
- });
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- pool.shutdown();
- }
-
- return "taskJksjSuccess";
- }
- public void taskJksjPool(int num) {
- System.out.println(Thread.currentThread().getName() + " " + taskJksj[num]);
-
- }
- public String poolExecutorJxdx() {
- ThreadPoolExecutor pool = new ThreadPoolExecutor(3, 10, 3, TimeUnit.SECONDS, new LinkedBlockingDeque<>(5), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
- try {
- for (int i = 0; i < taskJxdx.length; i++) {
- int num = i;
- pool.execute(() -> {
- taskJxdxPool(num);
- });
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- pool.shutdown();
- }
-
- return "taskJxdxSuccess";
- }
- public void taskJxdxPool(int num) {
- System.out.println(Thread.currentThread().getName() + " " + taskJxdx[num]);
- }
- public String poolExecutorNbzz() {
- ThreadPoolExecutor pool = new ThreadPoolExecutor(3, 10, 3, TimeUnit.SECONDS, new LinkedBlockingDeque<>(5), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
- try {
- for (int i = 0; i < taskNbzz.length; i++) {
- int num = i;
-
- pool.execute(() -> {
- taskNbzzPool(num);
- });
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- pool.shutdown();
- }
-
- return "taskNbzzSuccess";
- }
- public void taskNbzzPool(int num) {
- System.out.println(Thread.currentThread().getName() + " " + taskNbzz[num]);
- }
-
- }