zoukankan      html  css  js  c++  java
  • 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());
      }
       }});



  • 相关阅读:
    Java连接Mysql数据库异常:Public Key Retrieval is not allowed
    java8的时间段比较处理工具类TimeUtils
    MAVEN最常用的远程仓库
    maven的settings.xml配置阿里云中央仓库
    idea如何将java程序打包成exe可执行文件
    FakerUtil
    Golang内存逃逸是什么?怎么避免内存逃逸?
    10个高效Linux技巧及Vim命令对比[转]
    进程间8种通信方式详解
    基于openresty的URL 断路器/熔断器 -- URL-fuse
  • 原文地址:https://www.cnblogs.com/jxwy/p/6704925.html
Copyright © 2011-2022 走看看