unsafemultithreadpoolingsample.java

来自「这是一个关于J2EE的开源包common里的许多组件的示例应用程序,可以借鉴.」· Java 代码 · 共 71 行

JAVA
71
字号
/**
 * Title : Base Dict Class
 * Description : here Description is the function of class, here maybe multirows    
 * @author        kevin
 * @Version       1.0 
 */

package pool;

/**
 * Class description goes here.
 * @version 1.0  2005-12-5 
 * @author kevin
 */
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.impl.StackObjectPool;

class UnsafePicker extends Thread
{
	private ObjectPool pool;

	public UnsafePicker(ObjectPool op)
	{
		pool = op;
	}

	public void run()
	{
		Object obj = null;
		try
		{
			/* 似乎…… */
			if(pool.getNumActive() < 5)
			{
				sleep((long)(Math.random() * 10));
				obj = pool.borrowObject();
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}

public class UnsafeMultiThreadPoolingSample
{

	public static void main(String[] args)
	{
		ObjectPool pool = new StackObjectPool(new BasePoolableObjectFactorySample());
		Thread ts[] = new Thread[20];
		for(int j = 0; j < ts.length; j++)
		{
			ts[j] = new UnsafePicker(pool);
			ts[j].start();
		}
		try
		{
			Thread.sleep(1000);
			/* 然而…… */
			System.out.println("NumActive:" + pool.getNumActive());
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?