自定义线程池使用实例

自定义拒绝策略、自定义ThreadFactory、自定义线程池

package com.wucj.controller.thread;

import com.alibaba.fastjson.JSON;
import com.wucj.entity.MessageEntity;
import com.wucj.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * \* Created with IntelliJ IDEA.
 * \* @author: wucj
 * \* @date: 2020/1/27 14:49
 * \* @description:
 * \
 */
@Slf4j
public class ExcutorServiceSingle{
    /** 单例 **/
    private static ExcutorServiceSingle instance = null;
    /** 线程池管理类:使用自定义的拒绝策略**/
    private static ExecutorService executorService =
            new ThreadPoolExecutor(2, 5, 5,
                    TimeUnit.SECONDS, new ArrayBlockingQueue<>(10),
                    new MessageThreadFactory(),
                    new MessageRejectedExecutionHandler());

    private ExcutorServiceSingle() {

    }
    /** 获取单例 **/
    public static ExcutorServiceSingle getInstance(){
        if(null==instance){
            synchronized(ExcutorServiceSingle.class){
                instance = new ExcutorServiceSingle();
            }
        }
        return instance;
    }

    /** 发起异步执行 **/
    public void excutor(MessageEntity messageEntity){
        MessageRunable messageRunable = new MessageRunable(messageEntity);
        executorService.submit(messageRunable);
    }
    /**
     * Attempts to stop all actively executing tasks, halts the
     * processing of waiting tasks, and returns a list of the tasks
     * that were awaiting execution.
     *
     * <p>This method does not wait for actively executing tasks to
     * terminate.
     *
     * <p>There are no guarantees beyond best-effort attempts to stop
     * processing actively executing tasks.  For example, typical
     * implementations will cancel via {@link Thread#interrupt}, so any
     * task that fails to respond to interrupts may never terminate.
     *
     * @return list of tasks that never commenced execution
     * @throws SecurityException if a security manager exists and
     *         shutting down this ExecutorService may manipulate
     *         threads that the caller is not permitted to modify
     *         because it does not hold {@link
     *         java.lang.RuntimePermission}{@code ("modifyThread")},
     *         or the security manager's {@code checkAccess} method
     *         denies access.
     */
    public void shutDownNow(){
        List<Runnable> messageRunableList = executorService.shutdownNow();
        if(CollectionUtils.isEmpty(messageRunableList)){
            log.info("线程池关闭时,不存在正在执行的线程...");
        }else{
            String uuid = UUIDUtils.create();
            log.info("{}线程池关闭时,存在正在执行的线程...",uuid);
            for (Runnable runnable : messageRunableList) {
                log.info("{}线程池关闭时,存在线程:{}",uuid, JSON.toJSONString(runnable));
            }
        }
    }
    /**
     * Initiates an orderly shutdown in which previously submitted
     * tasks are executed, but no new tasks will be accepted.
     * Invocation has no additional effect if already shut down.
     * <p>This method does not wait for previously submitted tasks to
     * complete execution.
     *
     * @throws SecurityException {@inheritDoc}
     */
    public void shutDown(){
        executorService.shutdown();
    }
    /**
     * Returns {@code true} if this executor has been shut down.
     *
     * @return {@code true} if this executor has been shut down
     */
    public boolean isShutDown(){
        return executorService.isShutdown();
    }
}
package com.wucj.controller.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * \* Created with IntelliJ IDEA.
 * \* @author: wucj
 * \* @date: 2020/1/27 16:33
 * \* @description: 自定义线程池丢弃策略
 * \
 */
@Slf4j
public class MessageRejectedExecutionHandler implements RejectedExecutionHandler {
    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        log.info("消息推送超过异步任务的最大长度,执行拒绝策略,{}",executor.toString());
    }
}
package com.wucj.controller.thread;

import com.alibaba.fastjson.JSON;
import com.wucj.entity.MessageEntity;
import com.wucj.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * \* Created with IntelliJ IDEA.
 * \* @author: wucj
 * \* @date: 2020/1/27 14:55
 * \* @description:
 * \
 */
@Slf4j
public class MessageRunable implements Runnable{

    private MessageEntity messageEntity;

    public MessageRunable(MessageEntity messageEntity) {
        this.messageEntity = messageEntity;
    }

    @Override
    public void run() {
        String uuid = UUIDUtils.create();
        log.info("{}发送消息:{}",uuid, JSON.toJSONString(messageEntity));
        try {
            TimeUnit.SECONDS.sleep(60);
        } catch (InterruptedException e) {
            log.error("{}消息发送异常:{}",uuid,e);
        }
        log.info("{}消息发送完成",uuid);
    }
}
package com.wucj.controller.thread;

import java.util.concurrent.ThreadFactory;

/**
 * \* Created with IntelliJ IDEA.
 * \* @author: wucj
 * \* @date: 2020/1/27 15:26
 * \* @description: 线程组线程管理类
 * \
 */
public class MessageThreadFactory implements ThreadFactory {
    /** 线程所属组名称 **/
    private String groupName = "消息发送线程组";
    /** 线程名称 **/
    private String threadName = "消息发送线程名称";
    /** 栈大小 **/
    private int stackSize = 0;
    /** 线程组 **/
    private ThreadGroup threadGroup = new ThreadGroup(groupName);
    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(threadGroup,r,threadName,stackSize);
        if (t.isDaemon()){
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY){
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }
}

测试

@Data
public class MessageEntity {

    private String message;
    private String toUserName;
}
package com.wucj.controller;

import com.wucj.base.BaseResult;
import com.wucj.controller.thread.ExcutorServiceSingle;
import com.wucj.entity.MessageEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * \* Created with IntelliJ IDEA.
 * \* @author: wucj
 * \* @date: 2020/1/21 20:12
 * \* @description:
 * \
 */
@RestController
@Slf4j
@RequestMapping("api/thread")
public class ThreadController {

    @GetMapping("info")
    public BaseResult nowThreadInfo(){
        ThreadGroup group = Thread.currentThread().getThreadGroup();
        log.info("当前线程组的名称:",group.getName());
        Thread[] list1 = new Thread[group.activeCount()];
        group.enumerate(list1);
        for (Thread thread:list1){
            log.info("分组:{},名称:{}",group.getName(),thread.getName());
        }
        ThreadGroup groupParent = group.getParent();
        log.info("当前线程组的名称:",groupParent.getName());
        Thread[] list2 = new Thread[groupParent.activeCount()];
        groupParent.enumerate(list2);
        for (Thread thread:list2){
            log.info("分组:{},名称:{}",groupParent.getName(),thread.getName());
        }
        ThreadGroup groupParentT = groupParent.getParent();
        return BaseResult.success("操作成功");
    }

    @PostMapping("excutor")
    public BaseResult threadExcutoer(@RequestBody MessageEntity messageEntity){
        ExcutorServiceSingle excutorServiceSingle = ExcutorServiceSingle.getInstance();
        excutorServiceSingle.excutor(messageEntity);
        return BaseResult.success("操作成功");
    }

    @GetMapping("shutDownNow")
    public BaseResult shutDownNow(){
        ExcutorServiceSingle excutorServiceSingle = ExcutorServiceSingle.getInstance();
        try{
            excutorServiceSingle.shutDownNow();
            return BaseResult.success("停止成功");
        }catch (Exception e){
            log.error("停止线程池异常:{}",e);
            return BaseResult.success("停止异常");
        }
    }

    @GetMapping("shutDown")
    public BaseResult shutDown(){
        ExcutorServiceSingle excutorServiceSingle = ExcutorServiceSingle.getInstance();
        try{
            excutorServiceSingle.shutDown();
            return BaseResult.success("尝试停止成功");
        }catch (Exception e){
            log.error("尝试关闭线程池异常:{}",e);
            return BaseResult.success("尝试停止异常");
        }
    }

    @GetMapping("isShutDown")
    public BaseResult isShutDown(){
        ExcutorServiceSingle excutorServiceSingle = ExcutorServiceSingle.getInstance();
        try{
            boolean bool = excutorServiceSingle.isShutDown();
            if(bool){
                return BaseResult.success("线程池已经停止");
            }else{
                return BaseResult.success("线程池未停止");
            }
        }catch (Exception e){
            log.error("检查是否已经停止异常:{}",e);
            return BaseResult.success("检查是否已经停止异常");
        }
    }
}

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
线程池的自定义线程池工厂指的是我们可以通过自定义工厂类来创建线程池。在Java中,我们可以通过实现ThreadFactory接口来自定义线程池工厂。通过自定义工厂类,我们可以定制线程的创建方式,例如给线程设置特定的命名规则、设置线程的优先级等。 自定义线程池工厂的步骤如下: 1. 创建一个实现ThreadFactory接口的自定义工厂类,并实现其`newThread(Runnable r)`方法。 2. 在`newThread`方法中,我们可以通过`Thread`类的构造方法来创建线程,并进行一些定制化的操作,比如设置线程的名称、优先级等。 3. 自定义线程池工厂类的实例化后,我们可以将其作为参数传递给线程池创建方法中,以便使用定义线程池工厂来创建线程池。 举个例子,假设我们需要自定义线程池工厂来创建线程池,可以按照以下步骤进行: 1. 创建一个自定义线程池工厂类,例如`CustomThreadFactory`,并实现ThreadFactory接口。 2. 在`CustomThreadFactory`类中,实现`newThread(Runnable r)`方法,并在该方法中创建线程,并设置线程的名称。 3. 在使用线程池的地方,例如`Executors.newFixedThreadPool()`方法中,将`CustomThreadFactory`类的实例传递给`newFixedThreadPool()`方法,以使用定义线程池工厂来创建线程池。 通过自定义线程池工厂,我们可以更加灵活地控制线程的创建过程,并根据实际需求进行定制化操作。这样可以提高线程池的灵活性和可扩展性,使其更好地适用于各种场景的需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值