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

被折叠的 条评论
为什么被折叠?



