spring 异步操作

Java的异步操作通过多线程实现 。

线程的两种实现方式 :

 1、自定义一个类class ,继承Thread ,重写 Thread 类的run() 方法

 2、自定义一个类class,实现Runnable接口,实现run() 方法 。

 

Thread 方式 :

   example:

public class MyThread extends Thread {

/** 重写Thread的run() */
public void run(){
    /** 线程执行的操作*/
    System.out.println("hello thread");
}

public static void main(String[] args) {
Thread thread = new MyThread();
// 启动线程
thread.start();
}
}

Runable 实现方式 :

 (1). example

public class MyRunnable implements Runnable {

/** 实现run()方法 */
@Override
public void run() {
/** 线程执行的操作*/
System.out.println("hello Runnable");
}

public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();

}
}
(2).example2
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("hello ");
}
});
thread1.start();

异步 :

 最原始的方式,当我们要并行的或者异步的执行一个任务的时候,我们会使用以上方法启动一个线程。

缺点 :  

   1、每次new Thread新建对象性能差

   2、线程缺乏统一的管理,可以无限制新建线程,相互之间竞争,还可能占用过多系统资源导致死机或者OOM(Out of Memory);

 

Spring 的异步操作 : 使用线程池 :TaskExecutor 

  TaskExecutor的实现有很多,此次只针对具体的功能,使用 实现  ThreadPoolTaskExecutor

  以下操作是在spring 的环境能正常运行的情况下 :

  1、在xml文件中配置 :

   <bean id="taskExecutor"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"
p:corePoolSize="5" p:maxPoolSize="10" p:queueCapacity="100"
p:waitForTasksToCompleteOnShutdown="true" />

 2、在类中引入该bean

    @Resource(name="taskExecutor")
private TaskExecutor taskExecutor;

3、执行

  taskExecutor.execute(Runnable runnable);
  taskExecutor.execute(new Runnable(){
   public void run() {
      /**线程执行的操作 ×/   
       try {
   sendPushIService.sendPush(pushParams);
  } catch (ServiceException e) {
   log.error("send push error ,the cause : " + e.getMessage());
  }
   }});

 

 

 

 

 

 

 




转载于:https://www.cnblogs.com/jxwy/p/6704925.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值