Executors创建单个线程池为什么出现两个线程池

@Component
public class StatusListener implements ServletContextAware {

final ReentrantLock lock = new ReentrantLock();

@Override
public void setServletContext(ServletContext servletContext) {
    Runnable runnable = new Runnable() {
        public void run() {
            statusTask();
        }
    };

    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

    // 第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间
    service.scheduleAtFixedRate(runnable, 20, 60, TimeUnit.SECONDS);
}

public void statusTask() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        System.out.println(Thread.currentThread().getName());
        System.out.println(Thread.currentThread().getId());

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        lock.unlock();
    }
}

}

运行结果为:
pool-2-thread-1
40

pool-4-thread-1
42

阅读 1.8k
1 个回答

spring 初始化的时候,setServletContext 这个方法会调用二次(或者多次)。自己去看看api,所以你上面的代码会初始化了不止一个的线程连接池。
你可以自己试试,在setServletContext 方法中打印一句话,看看执行了几次。
注意看下面对应api的注释。

public interface ServletContextAware extends Aware {

    /**
     * Set the {@link ServletContext} that this object runs in.
     * <p>Invoked after population of normal bean properties but before an init
     * callback like InitializingBean's {@code afterPropertiesSet} or a
     * custom init-method. Invoked after ApplicationContextAware's
     * {@code setApplicationContext}.
     * @param servletContext ServletContext object to be used by this object
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
     * @see org.springframework.context.ApplicationContextAware#setApplicationContext
     */
    void setServletContext(ServletContext servletContext);

}
推荐问题