java线程池配置以及使用

applicationContext-threadpool.xml配置


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    
    <bean id="threadPoolTaskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
        
        <property name="corePoolSize" value="50" />
        
        <property name="maxPoolSize" value="1000" />
        
        <property name="queueCapacity" value="20000" />
        
        <property name="keepAliveSeconds" value="300" />
        
        <property name="rejectedExecutionHandler">
            
            
            
            
            <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
        property>
    bean>

beans>

线城市使用:线程池可以结合MQ来使用,也可以单独使用,这里展示和MQ结合使用

package com.zheng.api.server.jms;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

/**
 * MQ消费者
 * Created by shuzheng on 2017/2/19.
 */
public class DefaultMessageQueueListener implements MessageListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMessageQueueListener.class);

    @Autowired
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Override
    public void onMessage(final Message message) {
        // 使用线程池多线程处理
        threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                if (message instanceof TextMessage) {
                    TextMessage textMessage = (TextMessage) message;
                    try {
                        LOGGER.info("消费:{}", textMessage.getText());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

}

你可能感兴趣的:(java)