`
neil-jh
  • 浏览: 145536 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

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

阅读更多
例如:我希望用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调用者



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics