论坛首页 Java企业应用论坛

线程池示例代码,请大家多指教

浏览 25524 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (2) :: 隐藏帖 (13)
作者 正文
   发表时间:2009-08-14  
另外线程类不要继承Thread类,用来实现Runable接口等细节问题。
0 请登录后投票
   发表时间:2009-08-14  
以前见过一个,跟lz的类似
0 请登录后投票
   发表时间:2009-08-15  
学习了!!!!!
0 请登录后投票
   发表时间:2009-08-15  
发给你了 请查收.
0 请登录后投票
   发表时间:2009-08-15  
别的都不说了,希望楼主把java代码编辑一下,用Code标签吧。看起来太吃力了阿
0 请登录后投票
   发表时间:2009-08-15  
请在相应的代码上加上 synchronized;
你的代码在我的电脑上之能够运行到初始化结束;
0 请登录后投票
   发表时间:2009-08-16   最后修改:2009-08-16
因为过段时间可能要用到pool了,所以也提前学习下.

LZ的ThreadPool大致有几个这样的方法:

public void init(int count) // 初始化
public MyThread getFreeThread() // 获得
public void close() // 关闭pool


看了下apache的commons,也大致有如下几个方法:

Object borrowObject() // get an instance from pool
void returnObject(Object obj) // return an instrance to pool  (这点楼主应该是缺少的重要部分)
void invalidateObject(Object obj)  // invalidates the object when the object is determinded
void addObject() // create an object
int getNumIdle() // get the number of idle
int getNumActive() // return the number of instances currently borrowed from pool
void clear() // releasing any associated resources
void close() // close the pool and releasing any associated resources (类似LZ的close()了)


继续学习中...
0 请登录后投票
   发表时间:2009-08-16   最后修改:2009-08-16
稍微研究了下commons的代码.
commons的对象池比LZ的要强悍有如下几个方面(不全,望高手补充):
1,pool的每个进出object都进行类型检查
2,提供了一个线程安全的版本.
3,对当前active object和sleeping object的控制
4,对object的获取和释放的时间控制
5,容错处理

其他...
// 以下是commons项目中一个最简单的pool(对象是用Stack存储的),还有其他复杂的存储结构,对象数量控制和时间控制的pool现在还没看懂,呵呵,功力不够啊~ 先分享下晚上的学习成果吧(对这里的factory角色还没理解到位,只是做点简单阅读,还要向大家学习).


package java.org.apache.commons.pool.impl;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Stack;
import java.org.apache.commons.pool.BaseObjectPool;
import java.org.apache.commons.pool.ObjectPool;
import java.org.apache.commons.pool.PoolableObjectFactory;
/**
 *
 * @author Rodney Waldhoff  //三位作者
 * @author Dirk Verbeeck
 * @author Sandy McArthur
 * @version $Revision: 777748 $ $Date: 2009-05-23 08:00:44 +0800 $ //时间还比较新
 * @since Pool 1.0
 */
public class StackObjectPool extends BaseObjectPool implements ObjectPool {
  /** The default cap on the number of "sleeping" instances in the pool. */
    protected static final int DEFAULT_MAX_SLEEPING  = 8; // 池中最少保留对象数
    protected static final int DEFAULT_INIT_SLEEPING_CAPACITY = 4; // 初始化池中对象数

    /** My pool. */
    protected Stack _pool = null; // 用Stack存储池中对象

    /** My {@link PoolableObjectFactory}. */
    protected PoolableObjectFactory _factory = null; // 工厂对象

    /** The cap on the number of "sleeping" instances in the pool. */
    protected int _maxSleeping = DEFAULT_MAX_SLEEPING;

    /** Number of object borrowed but not yet returned to the pool. */
    protected int _numActive = 0; //当前对象活动数
    // 构造方法1
    public StackObjectPool() {
        this((PoolableObjectFactory)null,DEFAULT_MAX_SLEEPING,DEFAULT_INIT_SLEEPING_CAPACITY);
    }

    // 构造方法2
    public StackObjectPool(int maxIdle) {
        this((PoolableObjectFactory)null,maxIdle,DEFAULT_INIT_SLEEPING_CAPACITY);
    }

    // 构造方法3
    public StackObjectPool(int maxIdle, int initIdleCapacity) {
        this((PoolableObjectFactory)null,maxIdle,initIdleCapacity);
    }

    // 构造方法4
    public StackObjectPool(PoolableObjectFactory factory) {
        this(factory,DEFAULT_MAX_SLEEPING,DEFAULT_INIT_SLEEPING_CAPACITY);
    }

    // 构造方法5
    public StackObjectPool(PoolableObjectFactory factory, int maxIdle) {
        this(factory,maxIdle,DEFAULT_INIT_SLEEPING_CAPACITY);
    }

    /**
     * Create a new <tt>SimpleObjectPool</tt> using
     * the specified <i>factory</i> to create new instances,
     * capping the number of "sleeping" instances to <i>max</i>,
     * and initially allocating a container capable of containing
     * at least <i>init</i> instances.
     *
     * @param factory the {@link PoolableObjectFactory} used to populate the pool
     * @param maxIdle cap on the number of "sleeping" instances in the pool
     * @param initIdleCapacity initial size of the pool (this specifies the size of the container,
     *             it does not cause the pool to be pre-populated.)
     */
    public StackObjectPool(PoolableObjectFactory factory, int maxIdle, int initIdleCapacity) {
        _factory = factory;
        _maxSleeping = (maxIdle < 0 ? DEFAULT_MAX_SLEEPING : maxIdle);
        int initcapacity = (initIdleCapacity < 1 ? DEFAULT_INIT_SLEEPING_CAPACITY : initIdleCapacity);
        _pool = new Stack();
        _pool.ensureCapacity( initcapacity > _maxSleeping ? _maxSleeping : initcapacity); // at least the number of components
    }


     /**
     * Create an object, and place it into the pool.
     * addObject() is useful for "pre-loading" a pool with idle objects.
     * @throws Exception when the {@link #_factory} has a problem creating an object.
     */
    public synchronized void addObject() throws Exception {
        assertOpen(); // 检查pool是否关闭
        if (_factory == null) {
            throw new IllegalStateException("Cannot add objects without a factory.");
        }
        Object obj = _factory.makeObject(); // 创建一个可以被pool服务的对象

        boolean success = true;
        if(!_factory.validateObject(obj)) { // 进行新对象的类型检查
            success = false; 
        } else {
            _factory.passivateObject(obj); // Uninitialize an instance to be returned to the idle object pool.
        }

        boolean shouldDestroy = !success;

        if (success) {
            Object toBeDestroyed = null;
            if(_pool.size() >= _maxSleeping) { //  如果STATCK的大小大于pool的阀值,释放Stack中一个对象
                shouldDestroy = true;
                toBeDestroyed = _pool.remove(0); // remove the stalest object
	
            }
            _pool.push(obj);
            obj = toBeDestroyed; // swap returned obj with the stalest one so it can be destroyed
        }
        notifyAll(); // _numIdle has changed
	

	// 把以下代码写到这里的原因是 _factory可能是为null的,可支持无工厂对象池的创建
        if(shouldDestroy) { // by constructor, shouldDestroy is false when _factory is null
            try {
                _factory.destroyObject(obj); // 这里看得不是很明白
            } catch(Exception e) {
                // ignored
            }
        }
    }
    
    // 从对象池获取对象
    public synchronized Object borrowObject() throws Exception {
        assertOpen();
        Object obj = null;
        boolean newlyCreated = false;
        while (null == obj) {
            if (!_pool.empty()) {
                obj = _pool.pop();
            } else {
                if(null == _factory) {
                    throw new NoSuchElementException();
                } else {
                    obj = _factory.makeObject(); // 创建一个可以被pool服务的对象
                    newlyCreated = true;
                  if (obj == null) {
                    throw new NoSuchElementException("PoolableObjectFactory.makeObject() returned null.");
                  }
                }
            }
            if (null != _factory && null != obj) {
                try {
                    _factory.activateObject(obj); // 重新配置当前对象,准备给上层系统应用
                    if (!_factory.validateObject(obj)) { // 校验类型
                        throw new Exception("ValidateObject failed");
                    }
                } catch (Throwable t) {
                    try {
                        _factory.destroyObject(obj);
                    } catch (Throwable t2) {
                        // swallowed
                    } finally {
                        obj = null;
                    }
                    if (newlyCreated) {
                        throw new NoSuchElementException(
                            "Could not create a validated object, cause: " +
                            t.getMessage());
                    }
                }
            }
        }
        _numActive++; // 活动数量+1
        return obj;
    }
    
    // 返回一个对象给pool
    public synchronized void returnObject(Object obj) throws Exception {
        boolean success = !isClosed();
        if(null != _factory) { 
            if(!_factory.validateObject(obj)) { // 类型校验
                success = false;
            } else {
                try {
                    _factory.passivateObject(obj); // 卸载上层系统的对象,对象准备返回pool
                } catch(Exception e) {
                    success = false;
                }
            }
        }

        boolean shouldDestroy = !success;

        _numActive--;
        if (success) {
            Object toBeDestroyed = null;
            if(_pool.size() >= _maxSleeping) {
                shouldDestroy = true;
                toBeDestroyed = _pool.remove(0); // remove the stalest object
            }
            _pool.push(obj);
            obj = toBeDestroyed; // swap returned obj with the stalest one so it can be destroyed
        }
        notifyAll(); // _numActive has changed

        if(shouldDestroy) { // by constructor, shouldDestroy is false when _factory is null
            try {
                _factory.destroyObject(obj);
            } catch(Exception e) {
                // ignored
            }
        }
    }

    public synchronized void invalidateObject(Object obj) throws Exception {
        _numActive--;
        if (null != _factory) {
            _factory.destroyObject(obj); // 校验类型
        }
        notifyAll(); // _numActive has changed
    }

    /**
     * Return the number of instances
     * currently idle in this pool.
     *
     * @return the number of instances currently idle in this pool
     */
    public synchronized int getNumIdle() {
        return _pool.size();
    }

    /**
     * Return the number of instances currently borrowed from this pool.
     *
     * @return the number of instances currently borrowed from this pool
     */
    public synchronized int getNumActive() {
        return _numActive;
    }

    /**
     * Clears any objects sitting idle in the pool.
     */
    public synchronized void clear() {
        if(null != _factory) {
            Iterator it = _pool.iterator();
            while(it.hasNext()) {
                try {
                    _factory.destroyObject(it.next());
                } catch(Exception e) {
                    // ignore error, keep destroying the rest
                }
            }
        }
        _pool.clear();
    }

    /**
     * Close this pool, and free any resources associated with it.
     * <p>
     * Calling {@link #addObject} or {@link #borrowObject} after invoking
     * this method on a pool will cause them to throw an
     * {@link IllegalStateException}.
     * </p>
     *
     * @throws Exception <strong>deprecated</strong>: implementations should silently fail if not all resources can be freed.
     */
    public void close() throws Exception {
        super.close();
        clear();
    }

   
    /**
     * Sets the {@link PoolableObjectFactory factory} this pool uses
     * to create new instances. Trying to change
     * the <code>factory</code> while there are borrowed objects will
     * throw an {@link IllegalStateException}.
     *
     * @param factory the {@link PoolableObjectFactory} used to create new instances.
     * @throws IllegalStateException when the factory cannot be set at this time
     */
    public synchronized void setFactory(PoolableObjectFactory factory) throws IllegalStateException {
        assertOpen();
        if(0 < getNumActive()) {
            throw new IllegalStateException("Objects are already active");
        } else {
            clear();
            _factory = factory;
        }
    }
}



0 请登录后投票
   发表时间:2009-08-17  
jdk 1.5不是就有吗?何必再写一个。。。。
0 请登录后投票
   发表时间:2009-08-17  
用Excutor不是很好?线程这东西,能少尽量少.
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics