Java教程

Spring boot线程池与消息队列的使用线程安全

本文主要是介绍Spring boot线程池与消息队列的使用线程安全,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Spring boot线程池与消息队列的使用线程安全

import org.springframework.context.annotation.Bean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.concurrent.Executor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
@Slf4j
@Component
public class UdpQueueServer{
	//消息队列
	public static BlockingQueue queue = new ArrayBlockingQueue<>(1024);
	
	//设置线程池信息
	@Bean("taskExecutor")
	public Executor taskExecutor() {
		ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
		//最大线程数
		executor.setPoolSize(20);
		//线程名称
		executor.setThreadNamePrefix("处理数据-");
		executor.setWaitForTasksToCompleteOnShutdown(true);
		executor.setAwaitTerminationSeconds(10);
		return executor;
	}

	@Async("taskExecutor")	//与上方@Bean中值相同
    @Scheduled(fixedDelay = 3000)	//3秒启动一个线程
    public void consumerMessage() throws Exception {
        boolean isRunning = true;
        while (isRunning) {
            try {
				String con = (String) queue.take();		//取出队列中的数据
				if (con != null){
					log.info("内容:{}",con);
				} else {
					log.info("取出内容为null");
				}
				if(queue.remainingCapacity == 1024){
					isRunning = false;
				}
            } catch (Exception e) {
                e.printStackTrace();
                log.info("{}",e);
            }
        }
    }
}

线程池详细信息:https://blog.csdn.net/weixin_43583693/article/details/115675877

这篇关于Spring boot线程池与消息队列的使用线程安全的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!