用N个线程不停的跑业务逻辑

本文介绍如何使用Spring框架实现一个简单的线程池应用。通过创建自定义的ProductService类实现Runnable接口来定义业务逻辑,并利用ProductInvoker类在容器启动时初始化5个线程。文章详细展示了如何在Spring配置文件中配置这些组件。
例如:我希望用5个线程不停的跑一个业务逻辑,直到容器关闭为止。
业务逻辑ProductService 此业务逻辑用来在线程中跑,所以需要继承Runnable

public class ProductService implements Runnable{

private int id;

public ProductService(int threadId){
this.id = threadId;
}

...

public void run()
{
try
{
logger.info( "延迟60秒 启动发送线程..." );
Thread.sleep( 60000 );
}
catch ( InterruptedException e )
{
e.printStackTrace();
logger.error( "InterruptedException 线程退出..." );
}

while ( true ) //让线程一直跑下去
{

logger.info( "线程 【" + this.id + "】 开始运行 ......" );
try
{
this.send();
}
catch ( Exception e )
{
logger.error( "发送产生异常..." );

StringWriter sw = new StringWriter();
e.printStackTrace( new PrintWriter( sw ) );
logger.error( sw.toString() );
}


}

/**
* 主方法体;
*/
public void send(){
.....
}

...

}



之后需要一个线程生成并调用者,希望容器启动就开始生成这5个线程,所以继承spring的InitializingBean
ProductInvoker

public class ProductInvoker implements InitializingBean{
public void afterPropertiesSet() throws Exception{

for(int i=1;i<=5;i++)
{
ProductService r = new ProductService(i);
Thread _thread = new Thread(r);
_thread.start();
}

}

}


在spring配置文件中注入这个ProductInvoker调用者
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值