新手一枚,对该类多线程的运行原理不是很懂,为什么要用多线程,该类在spring ioc容器中注册,是单例的,为什么要加锁?谢谢
public class IdleConnectionEvictor extends Thread{
private final HttpClientConnectionManager connMgr;
private volatile boolean shutdown;
public IdleConnectionEvictor(HttpClientConnectionManager connMgr) {
this.connMgr = connMgr;
this.start();//刚创建就启动线程
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(5000);
// 关闭失效的连接
connMgr.closeExpiredConnections();
}
}
} catch (InterruptedException ex) {
// 结束
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}
<bean id="connectionManager"
class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager">
<!-- 设置最大连接数 -->
<property name="maxTotal" value="${httpclient.maxTotal}"></property>
<!-- 设置每个主机地址的并发数 -->
<property name="defaultMaxPerRoute" value="${httpclient.defaultMaxPerRoute}"></property>
</bean>
<bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder">
<!-- 设置连接管理器 -->
<property name="connectionManager" ref="connectionManager"></property>
</bean>
<!-- Httpclient对象 -->
<bean id="httpClient" class="org.apache.http.impl.client.CloseableHttpClient"
factory-bean="httpClientBuilder" factory-method="build" scope="prototype">
</bean>
<!-- 请求配置信息构建器 -->
<bean id="requestConfigBuilder" class="org.apache.http.client.config.RequestConfig.Builder">
<!-- 创建连接的最长时间 -->
<property name="connectTimeout" value="${httpclient.connectTimeout}" />
<!-- 从连接池中获取到连接的最长时间 -->
<property name="connectionRequestTimeout" value="${httpclient.connectionRequestTimeout}" />
<!-- 数据传输的最长时间 -->
<property name="socketTimeout" value="${httpclient.socketTimeout}" />
<!-- 提交请求前测试连接是否可用 -->
<property name="staleConnectionCheckEnabled" value="${httpclient.staleConnectionCheckEnabled}" />
</bean>
<!-- 设置请求配置信息 -->
<bean id="requestConfig" class="org.apache.http.client.config.RequestConfig"
factory-bean="requestConfigBuilder" factory-method="build">
</bean>
<!-- 定时清理Connection -->
<bean id="idleConnectionEvictor" class="com.xxx.front.httpclient.IdleConnectionEvictor"
destroy-method="shutdown"><!-- 销毁的方法 -->
<constructor-arg index="0" ref="connectionManager" />
</bean>