Spring之十三 线程池

线程池 ThreadPoolTaskExecutor

1.applicationContext.xml中配置

    <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
        <!--线程池活跃的线程数-->
        <property name="corePoolSize" value="5" />
        <!--线程池最大活跃的线程数-->
        <property name="maxPoolSize" value="150" />
        <!--任务队列的最大容量-->
        <property name="queueCapacity" value="5000" />
        <!--线程池维护线程所允许的空闲时间-->
        <property name="keepAliveSeconds" value="60" />
        <!-- 线程池对无线程可用的处理策略-->
        <property name="rejectedExecutionHandler">
            <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
        </property>
    </bean>

2.使用

	TaskExecutor taskExecutor = (TaskExecutor)SpringContextUtil.getBean("taskExecutor");
	taskExecutor.execute(new personRunner());

守护线程

1.实现ThreadFactory接口

public class HelloThreadFactory implements ThreadFactory{
    private final static HelloThreadFactory instance = new HelloThreadFactory();
    private final ThreadGroup group;

    /**
     * 构造函数
     */
    public HelloThreadFactory() {
        this(null);
    }
    
    public HelloThreadFactory(ThreadGroup group) {
        if(group == null){
            SecurityManager s = System.getSecurityManager();
            this.group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        }else{
            this.group = group;
        }
    }
    
    public static HelloThreadFactory getInstance(){
        return instance;
    }
    
    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r);
        return t;
    }
    
    //启动守护线程
    public void startDaemonThread(Thread t, String threadName){
        if(null == t){
            return;
        }
        t.setDaemon(true);
        t.setName(threadName);
        t.start();
    }
}

2.使用线程工厂创建线程

@Component
public class HelloInit {
    public void init(){
        HelloThreadFactory threadFactory = HelloThreadFactory.getInstance();
        Thread testThread = threadFactory.newThread(new TestThread());
        threadFactory.startDaemonThread(testThread, "test");
    }
}


3.在Spring的监听文件中初始化

public class SystemListener extends ContextLoaderListener{
    
    @Override
    public void contextInitialized(ServletContextEvent event) {
        //启动spring环境
        super.contextInitialized(event); 
        HelloInit helloInit = (HelloInit)SpringContextUtil.getBean(HelloInit.class);
        helloInit.init();
    }
}

注:若不使用线程工厂,需要new Thread

	Thread thread = new Thread(new TestThread());
	thread.setDaemon(true);
	thread.start();
	





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值