线程池代码完整剖析(一)

线程池代码完整剖析(一)

一、概述

 

    Jetty一个重要的组件就是线程池,本文主要是围绕源代码是怎样开发一个线程池,因为有一个任务需要处理,就直接从线程池里面取出一个线程,这样就加快应用程序的速度。

要开发一个线程池主要要注意的几个地方:

 

1、先要定义一个集合,这个集合主要是保存线程池里面的线程数目

2、因为线程池里面的线程不可能所有的线程都需要工作,所以要在定义一个集合专门用来保存线程池里面空闲的线程

3、然后,开发中不可能线程越多越好,这样会影响应用程序的性能,所以必须要定义变量,线程池中最大的线程和最小的线       程数目

4、如果任务的请求量已经把线程池中的线程数目都占有(没有了空闲线程),那么必须定义一个队列:把请求的任务存放在队列中,等有空闲的线程,在从队列中取出来。

5、如果队列的任务已经很多(必须限制队列的长度)来不及处理,这样会影响任务处理的速度

6、如果线程池中的数目空闲线程已经达到了线程池中最小的数目时候,必须要清理一些空闲的线程,就需要定义线程的生命周 期。

7、必须要妥善的处理线程池中的数目,在什么时候线程池的数目要增加,在什么情况下线程池中的数目要减少

8、如何安全的关闭一个线程

9、涉及到多线程问题,代码块如何进行同步

 

在这里举出了九个问题,读者可以带着九个问题思考,看Jetty线程池代码是如何解决。

 

二、讲述源代码

 

Jetty中实现线程池就用了一个接口和一个实现的类。

 

下面为了说明问题先讲一个组件:LifeCycle--就是Jetty是如何优雅的实现每个组件开启和关闭

 

下面看LifeCycle接口源代码:

 

public interface LifeCycle
{
    /* ------------------------------------------------------------ */
    /**
     * Starts the component.
     * @throws Exception If the component fails to start
     * @see #isStarted()
     * @see #stop()
     * @see #isFailed()
     */
    public void start()
        throws Exception;

    /* ------------------------------------------------------------ */
    /**
     * Stops the component.
     * The component may wait for current activities to complete
     * normally, but it can be interrupted.
     * @exception Exception If the component fails to stop
     * @see #isStopped()
     * @see #start()
     * @see #isFailed()
     */
    public void stop()
        throws Exception;

    /* ------------------------------------------------------------ */
    /**
     * @return true if the component is starting or has been started.
     */
    public boolean isRunning();

    /* ------------------------------------------------------------ */
    /**
     * @return true if the component has been started.
     * @see #start()
     * @see #isStarting()
     */
    public boolean isStarted();

    /* ------------------------------------------------------------ */
    /**
     * @return true if the component is starting.
     * @see #isStarted()
     */
    public boolean isStarting();

    /* ------------------------------------------------------------ */
    /**
     * @return true if the component is stopping.
     * @see #isStopped()
     */
    public boolean isStopping();

    /* ------------------------------------------------------------ */
    /**
     * @return true if the component has been stopped.
     * @see #stop()
     * @see #isStopping()
     */
    public boolean isStopped();

    /* ------------------------------------------------------------ */
    /**
     * @return true if the component has failed to start or has failed to stop.
     */
    public boolean isFailed();
    
    /* ------------------------------------------------------------ */
    public void addLifeCycleListener(LifeCycle.Listener listener);

    /* ------------------------------------------------------------ */
    public void removeLifeCycleListener(LifeCycle.Listener listener);
    

    /* ------------------------------------------------------------ */
    /** Listener.
     * A listener for Lifecycle events.
     */
    public interface Listener extends EventListener
    {
        public void lifeCycleStarting(LifeCycle event);
        public void lifeCycleStarted(LifeCycle event);
        public void lifeCycleFailure(LifeCycle event,Throwable cause);
        public void lifeCycleStopping(LifeCycle event);
        public void lifeCycleStopped(LifeCycle event);
    }
}

 

该接口里面有一个内部接口Listener,主要是外面注册监听事件:组件是正在开始、已经开始、正在停止、已经停止、失败了,全部依赖这五个方法。

下面是实现这个接口的抽象类:AbstractLifeCycle

代码请看下面:

 

public abstract class AbstractLifeCycle implements LifeCycle
{
	//这个也是抽象类加锁的一个解决方案
    private Object _lock = new Object();
    private final int FAILED = -1, STOPPED = 0, STARTING = 1, STARTED = 2, STOPPING = 3;
    private transient int _state = STOPPED;
    protected LifeCycle.Listener[] _listeners;

    protected void doStart() throws Exception
    {
    }

    protected void doStop() throws Exception
    {
    }

    public final void start() throws Exception
    {
        synchronized (this)
        {
            try
            {
                if (_state == STARTED || _state == STARTING)
                    return;
                setStarting();
                doStart();
                Log.debug("started {}",this);
                setStarted();
            }
            catch (Exception e)
            {
                setFailed(e);
                throw e;
            }
            catch (Error e)
            {
                setFailed(e);
                throw e;
            }
        }
    }

    public final void stop() throws Exception
    {
        synchronized (_lock)
        {
            try
            {
                if (_state == STOPPING || _state == STOPPED)
                    return;
                setStopping();
                doStop();
                Log.debug("stopped {}",this);
                setStopped();
            }
            catch (Exception e)
            {
                setFailed(e);
                throw e;
            }
            catch (Error e)
            {
                setFailed(e);
                throw e;
            }
        }
    }

    public boolean isRunning()
    {
        return _state == STARTED || _state == STARTING;
    }

    public boolean isStarted()
    {
        return _state == STARTED;
    }

    public boolean isStarting()
    {
        return _state == STARTING;
    }

    public boolean isStopping()
    {
        return _state == STOPPING;
    }

    public boolean isStopped()
    {
        return _state == STOPPED;
    }

    public boolean isFailed()
    {
        return _state == FAILED;
    }

    public void addLifeCycleListener(LifeCycle.Listener listener)
    {
        _listeners = (LifeCycle.Listener[])LazyList.addToArray(_listeners,listener,LifeCycle.Listener.class);
    }

    public void removeLifeCycleListener(LifeCycle.Listener listener)
    {
        LazyList.removeFromArray(_listeners,listener);
    }

    private void setStarted()
    {
        _state = STARTED;
        if (_listeners != null)
        {
            for (int i = 0; i < _listeners.length; i++)
            {
                _listeners[i].lifeCycleStarted(this);
            }
        }
    }

    private void setStarting()
    {
        _state = STARTING;
        if (_listeners != null)
        {
            for (int i = 0; i < _listeners.length; i++)
            {
                _listeners[i].lifeCycleStarting(this);
            }
        }
    }

    private void setStopping()
    {
        _state = STOPPING;
        if (_listeners != null)
        {
            for (int i = 0; i < _listeners.length; i++)
            {
                _listeners[i].lifeCycleStopping(this);
            }
        }
    }

    private void setStopped()
    {
        _state = STOPPED;
        if (_listeners != null)
        {
            for (int i = 0; i < _listeners.length; i++)
            {
                _listeners[i].lifeCycleStopped(this);
            }
        }
    }

    private void setFailed(Throwable th)
    {
        Log.warn("failed "+this+": "+th);
        Log.debug(th);
        _state = FAILED;
        if (_listeners != null)
        {
            for (int i = 0; i < _listeners.length; i++)
            {
                _listeners[i].lifeCycleFailure(this,th);
            }
        }
    }

}

  private final int FAILED = -1, STOPPED = 0, STARTING = 1, STARTED = 2, STOPPING = 3;

    private transient int _state = STOPPED;

    protected LifeCycle.Listener[] _listeners;

_state是组件的状态变量,变量的值在上面所示,而组件所监听的事件是用一个数组表示 LifeCycle.Listener[] _listeners,还需要注意的是该抽象类定义了一个模板方法,doStart()和doStop()方法,具体代码留给实现的子类实现。

该设计就是典型的设计模式模板方法。。。。。还要注意的是LazyList类是Jetty定义的一个类,封装了一个集合。

 

下面具体剖析请看续集。。。。

 

 

 

你可能感兴趣的:(设计模式,多线程)