线程池基础

线程池基础

参考

线程池的使用(线程池重点解析)

相关类

接口

java.util.concurrent.Executor

java.util.concurrent.Executors

public interface Executor {
    /*
    可以使用一个线程,线程池,调用线程来实现。
     */
    void execute(Runnable command);
}

实现类

java.util.concurrent.ScheduledThreadPoolExecutor 有任务调度功能的线程池

java.util.concurrent.ThreadPoolExecutor 普通的线程池

核心构造器

public ThreadPoolExecutor(int corePoolSize,//核心线程池大小
                          int maximumPoolSize,//最大线程池大小
                          long keepAliveTime,//有效时间
                          TimeUnit unit,//时间单位
                          BlockingQueue<Runnable> workQueue,//任务队列
                          ThreadFactory threadFactory,//线程工厂
                          RejectedExecutionHandler handler);//拒绝执行处理器

示例

package com.mozq.boot.kuayu01.demo;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Thread_02 {
    /*
    线程池中创建2个线程,并执行。
    核心线程只有1个,添加了2个任务,第2个任务在第1个任务执行完毕后才开始执行。
    运行结果:
        main...start
        main...end
        pool-1-thread-1 1...
        pool-1-thread-1 1...
        pool-1-thread-1 1...
        pool-1-thread-1 2...
        pool-1-thread-1 2...
     */
    public static void main(String[] args) {
        System.out.println("main...start");
        /*
        最后调用super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue())
        
        */
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        //任务1
        scheduledExecutorService.schedule(new Thread(()->{
            int time = 3;
            while (time-- > 0){
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " 1...");
            }
        }), 0, TimeUnit.MICROSECONDS);
        //任务2
        scheduledExecutorService.schedule(new Thread(()->{
            while (true){
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " 2...");
            }
        }), 0, TimeUnit.MICROSECONDS);
        System.out.println("main...end");
    }
}
原文地址:https://www.cnblogs.com/mozq/p/12001563.html