Spring之多线程

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/carson0408/article/details/86348202

        开发中多线程与并发编程是必不可少的,而Spring中也有相应的工具类来实现这一功能,使用ThreadPoolTaskExecutor可实现一个基于线程池的TaskExecutor。联系实际,一般开发中常用异步任务,因此需要在Spring中实现异步任务主要有两步:

1.在配置类中通过@EnableAsync开启对异步任务的支持。

2.在实际执行的Bean的方法中使用@Async注解来声明其是一个异步任务。

        首先了解一下何为异步任务,异步是相对同步而言的,所谓同步就是任务一个个有序完成的,会出现阻塞情况;而异步则是执行一个任务,将任务在后台挂起,然后继续执行程序,等后台任务处理完毕后就返回结果,所以异步就是无阻塞、无序的。

        本文将举一个例子进行比较两者的区别。

1.配置类

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * 实现一个基于线程池的taskExecutor
 * 
 */
@Configuration
@ComponentScan("com.carson.taskdemo")
@EnableAsync
public class TaskExecutorConfig implements AsyncConfigurer {
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(5);
        taskExecutor.setMaxPoolSize(10);
        taskExecutor.setQueueCapacity(20);
        taskExecutor.initialize();
        return taskExecutor;
    }

    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}

2.任务执行类

        这里主要同步和异步的区别主要是@Async注解,该注解修饰类时,则表明该类的所有方法都是异步方法,修饰方法时表示该方法是异步方法。以下分别是同步和异步的代码:

同步:

package com.carson.taskdemo;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncTaskService {


    //@Async
    public void test1(Integer i){
        System.out.println("执行任务:"+i);
    }
    //@Async
    public void test2(Integer i){
        System.out.println("执行任务+1:"+(i+1));
    }
}

异步:

package com.carson.taskdemo;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncTaskService {


    @Async
    public void test1(Integer i){
        System.out.println("执行任务:"+i);
    }
    @Async
    public void test2(Integer i){
        System.out.println("执行任务+1:"+(i+1));
    }
}

3.运行类

package com.carson.taskdemo;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskExecutorConfig.class);

        AsyncTaskService  asyncTaskService = context.getBean(AsyncTaskService.class);

        for(int i=0;i<10;i++){
            asyncTaskService.test1(i);
            asyncTaskService.test2(i);
        }
        context.close();
    }
}

运行结果如下:

同步:

一月 12, 2019 10:39:08 上午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@4437c4: startup date [Sat Jan 12 10:39:08 CST 2019]; root of context hierarchy
一月 12, 2019 10:39:08 上午 org.springframework.context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker postProcessAfterInitialization
信息: Bean 'taskExecutorConfig' of type [class com.carson.taskdemo.TaskExecutorConfig$$EnhancerBySpringCGLIB$$141c69f3] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
一月 12, 2019 10:39:08 上午 org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor initialize
信息: Initializing ExecutorService 
一月 12, 2019 10:39:08 上午 org.springframework.context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker postProcessAfterInitialization
信息: Bean 'org.springframework.scheduling.annotation.ProxyAsyncConfiguration' of type [class org.springframework.scheduling.annotation.ProxyAsyncConfiguration$$EnhancerBySpringCGLIB$$150bf3d2] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
一月 12, 2019 10:39:08 上午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@4437c4: startup date [Sat Jan 12 10:39:08 CST 2019]; root of context hierarchy
执行任务:0
执行任务+1:1
执行任务:1
执行任务+1:2
执行任务:2
执行任务+1:3
执行任务:3
执行任务+1:4
执行任务:4
执行任务+1:5
执行任务:5
执行任务+1:6
执行任务:6
执行任务+1:7
执行任务:7
执行任务+1:8
执行任务:8
执行任务+1:9
执行任务:9
执行任务+1:10

Process finished with exit code 0

异步:

一月 12, 2019 10:37:31 上午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@4437c4: startup date [Sat Jan 12 10:37:31 CST 2019]; root of context hierarchy
一月 12, 2019 10:37:31 上午 org.springframework.context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker postProcessAfterInitialization
信息: Bean 'taskExecutorConfig' of type [class com.carson.taskdemo.TaskExecutorConfig$$EnhancerBySpringCGLIB$$fb152f6b] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
一月 12, 2019 10:37:31 上午 org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor initialize
信息: Initializing ExecutorService 
一月 12, 2019 10:37:31 上午 org.springframework.context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker postProcessAfterInitialization
信息: Bean 'org.springframework.scheduling.annotation.ProxyAsyncConfiguration' of type [class org.springframework.scheduling.annotation.ProxyAsyncConfiguration$$EnhancerBySpringCGLIB$$fc04b94a] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
一月 12, 2019 10:37:31 上午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@4437c4: startup date [Sat Jan 12 10:37:31 CST 2019]; root of context hierarchy
执行任务:0
执行任务:2
执行任务+1:1
执行任务+1:3
执行任务+1:4
执行任务+1:5
执行任务+1:2
执行任务+1:6
执行任务:1
执行任务+1:7
执行任务:6
执行任务+1:8
执行任务:5
执行任务+1:9
执行任务:9
执行任务:4
执行任务:3
执行任务+1:10
执行任务:8
执行任务:7

        比较两种结果可以看出同步的是有序的,而异步的则是并发执行的。

猜你喜欢

转载自blog.csdn.net/carson0408/article/details/86348202
今日推荐