SpringBoot使用自定义线程池

SpringBoot使用自定义线程池,第1张

SpringBoot使用自定义线程

使用场景:

方法处理到某一步,需要将信息交给另一个线程去处理!!

第一种:最简单的Runnable

//创建一个Runnable,重写run方法
public Runnable dealMsg(String msg){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("新开线程中处理:"+msg);
            }
        };

        return runnable;
    }
 public void test(String msg){
        System.out.println(Thread.currentThread().getName()+":"+msg);
        Runnable runnable = dealMsg(msg);
    //将返回的runnable对象传入,并start()启动线程
     new Thread(runnable).start();
    }

第二种:自己创建JDK线程池,交给spring管理,然后将任务交给线程池即可

1.创建线程池,交给spring管理

import com.example.recordlog.threadFactory.CustomThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;



@Configuration
public class ThreadPoolConfig {

    @Bean(name = "customThreadExecutor")
    public ExecutorService nlpFeignExecutor() throws Exception {
        ExecutorService executor = new ThreadPoolExecutor(4, 8,
                0L, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(5), new CustomThreadFactory("custom-Thread-pool"), new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
                try {
                    e.getQueue().put(r);
                } catch (InterruptedException e1) {
                    Thread.currentThread().interrupt();
                }
            }
        });
        return executor;
    }

}

自定义实现ThreadFactory

import java.util.concurrent.atomic.AtomicInteger;



public class CustomThreadFactory implements java.util.concurrent.ThreadFactory {


    private AtomicInteger threadNo = new AtomicInteger(1);

    private final String nameStart;

    private final String nameEnd = "]";

    public CustomThreadFactory(String poolName) {
        this.nameStart = "[" + poolName + "-";
    }

    @Override
    public Thread newThread(Runnable r) {
        String threadName = this.nameStart + this.threadNo.getAndIncrement() + "]";
        Thread newThread = new Thread(r, threadName);
        newThread.setDaemon(true);
        if (newThread.getPriority() != 5) {
            newThread.setPriority(5);
        }
        return newThread;
    }
}

使用自定义线程池

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.concurrent.ExecutorService;

@Controller
@RequestMapping("/custom")
@Slf4j
public class ThreadPoolTest {


    @Autowired
    @Qualifier(value = "customThreadExecutor")
    ExecutorService executorService;


    @RequestMapping(value = "/thread", method = RequestMethod.GET)
    public String task() {

        for (int i = 0; i < 5; i++) {
            executorService.execute(() -> {
                //实现逻辑
                System.out.println(Thread.currentThread() + "正在执行");
            });
        }
        return "OK";
    }

}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5637359.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存