线程池 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();