前边两章介绍了基础线程池ThreadPoolExecutor的使用方式、工作机理、参数详细介绍以及核心源码解析。

具体的介绍请参照:

第十二章 ThreadPoolExecutor使用与工作机理

第十三章 ThreadPoolExecutor源码解析

1、Executors与ThreadPoolExecutor

  • ThreadPoolExecutor
    • 可以灵活的自定义的创建线程池,可定制性很高
    • 想创建好一个合适的线程池比较难
    • 使用稍微麻烦一些
    • 实际中很少使用
  • Executors
    • 可以创建4种线程池,这四种线程池基本上已经包含了所有需求,将来根据业务特点选用就好
    • 使用非常简单
    • 实际中很常用

 使用方法:

package com.collection.test;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class ThreadPoolExecutorTest {
    //private static ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
    //private static Executor executor = Executors.newFixedThreadPool(5);
    //private static Executor executor = Executors.newSingleThreadExecutor();
    //private static Executor executor = Executors.newCachedThreadPool();
    private static Executor executor = Executors.newScheduledThreadPool(5);
    
    public void executeTask(){
        Task1 task1 = new Task1();//构建任务1
        Task2 task2 = new Task2();//构建任务2
        executor.execute(task1);//执行任务1
        executor.execute(task2);//执行任务2
    }
    
    /*
     * 基本任务2
     */
    class Task1 implements Runnable{
        public void run() {
            //具体任务的业务
            for(int i=0;i<1000;i++){
                System.out.println("hello xxx!!!");
            }
        }
    }
    
    /*
     * 基本任务2
     */
    class Task2 implements Runnable{
        public void run() {
            //具体任务的业务
            for(int i=0;i<5;i++){
                System.out.println("hello world2!!!");
            }
        }
    }
    
    public static void main(String[] args) {
        ThreadPoolExecutorTest test = new ThreadPoolExecutorTest();
        test.executeTask();
    }
}
View Code

相关文章:

  • 2022-12-23
  • 2021-10-23
  • 2022-01-13
  • 2022-02-13
  • 2021-06-28
  • 2021-10-21
  • 2021-10-14
  • 2021-10-01
猜你喜欢
  • 2021-11-19
  • 2021-06-25
  • 2022-02-17
  • 2021-11-11
  • 2021-10-23
  • 2021-11-20
  • 2022-12-23
相关资源
相似解决方案