近日读org.apache.log下源文件,根据其org.apache.log.output.AsyncLogTarget封装了一个动作处理池。像写日志、做事务不相关的其他处理或业务不相关的处理,交给另外的线程做是一个更好的策略。
DoAction,线程管理者,负责执行添加进去的线程。
package protect;
import java.util.LinkedList;
public class DoAction
implements Runnable
{
private final LinkedList m_list;
private final int m_queueSize;
public DoAction( final int queueSize )
{
m_list = new LinkedList();
m_queueSize = queueSize;
}
public void doAction( final Action event )
{
synchronized( m_list )
{
int size = m_list.size();
// 链表容量将满
while( m_queueSize <= size )
{
try
{
// 阻塞掉自�? // 当处理线程处理后notify 会被唤醒,唤醒后继续 询问大小 直到大小条件满足 循环才得以执行玩 。下边的添加
// 才会被执�?
m_list.wait();
}
catch( final InterruptedException ie )
{
//This really should not occur ...
//Maybe we should log it though for
//now lets ignore it
}
size = m_list.size();
}
m_list.addFirst( event );
// size==0 当是经过上行代码的添�? 链表已经不是空了,不是空的时�? 唤醒子线程的处理代码
if( size == 0 )
{
//tell the "server" thread to wake up
//if it is waiting for a queue to contain some items
m_list.notify();
}
}
}
/**
* Thread startup.
*/
public void run()
{
//set this variable when thread is interupted
//so we know we can shutdown thread soon.
boolean interupted = false;
while( true )
{
Action event = null;
synchronized( m_list )
{
while( null == event )
{
final int size = m_list.size();
if( size > 0 )
{
event = m_list.removeLast();
if( size == m_queueSize )
{
//tell the "client" thread to wake up
//if it is waiting for a queue position to open up
m_list.notify();
}
}
else if( interupted || Thread.interrupted() )
{
//ie there is nothing in queue and thread is interrupted
//thus we stop thread
return;
}
else
{
// 如果 当前容器中没有元素了,阻塞掉自己,没有必要再 �?直循�? 查找有无 元素
try
{
m_list.wait();
}
catch( final InterruptedException ie )
{
//Ignore this and let it be dealt in next loop
//Need to set variable as the exception throw cleared status
interupted = true;
}
}
}// end while
}// end syn
try
{
//actually process an event
event.doAction();
}
catch( final Throwable throwable )
{
}
}
}
}
每个动作接口:
package protect;
public interface Action {
public void doAction();
}
package protect;
public interface Action { public void doAction();}
举例测试:
package protect;
public class ExampleAction implements Action {
private String message;
public void doAction() {
// TODO Auto-generated method stub
System.out.println("show message:"+message);
}
public ExampleAction(String msg){
message=msg;
}
}
package protect;
import junit.framework.TestCase;
public class DoActionTest extends TestCase {
private DoAction dos;
protected void setUp() throws Exception {
// TODO Auto-generated method stub
super.setUp();
dos=new DoAction(10);
Thread t1=new Thread(dos);
t1.start();
}
public void testDoAction() throws Exception {
Action a=null;
for(int i=0;i<100;i++){
a=new ExampleAction(""+i);
dos.doAction(a);
}
}
}
转载自我的网站:
http://itrblog.info