springboot开启异步任务@Async,@EnableAsync

 

package com.cobra.appactiviti.task;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.concurrent.Future;

/**
 * @author: yaobin
 * @date: 2019/8/2
 * @description:
 */
@Component
public class AsyncTasks {

    @Async
    public Future doTaskOne() throws InterruptedException {

        Long time1 = System.currentTimeMillis();

        Thread.sleep(5000L);

        Long time2 = System.currentTimeMillis();

        System.out.println("doTaskOne耗时:"+(time2-time1));

        return new AsyncResult<>("AsyncTaskOne Finished");
    }

    @Async
    public Future doTaskTwo() throws InterruptedException {

        Long time1 = System.currentTimeMillis();

        Thread.sleep(2000L);

        Long time2 = System.currentTimeMillis();

        System.out.println("doTaskTwo耗时:"+(time2-time1));

        return new AsyncResult<>("AsyncTaskTwo Finished");
    }

    @Async
    public Future doTaskThree() throws InterruptedException {

        Long time1 = System.currentTimeMillis();

        Thread.sleep(3000L);

        Long time2 = System.currentTimeMillis();

        System.out.println("doTaskThree耗时:"+(time2-time1));

        return new AsyncResult<>("AsyncTaskThree Finished");
    }

}

 

package com.cobra.appactiviti.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author: yaobin
 * @date: 2019/8/3
 * @description:
 */
@Configuration
@EnableAsync
public class ExecutorConfig {
    
    private int corePoolSize = 10;

    private int maxPoolSize = 200;

    private int queueCapacity = 10;

    /**
     * @Bean("2")加上名后,executor.setThreadNamePrefix("mySecondAsync-")无效
     * 只用executor.setThreadNamePrefix("mySecondAsync-")时,@Async("mySecondAsync")
     * @return
     */
    @Bean("1")
    public Executor myFistAsync() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix("myFistAsync-");
        executor.initialize();
        return executor;
    }

    /**
     * @Bean("2")加上名后,executor.setThreadNamePrefix("mySecondAsync-")无效
     * 只用executor.setThreadNamePrefix("mySecondAsync-")时,@Async("mySecondAsync")
     * @return
     */
    @Bean("2")
    public Executor mySecondAsync() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix("mySecondAsync-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }


}

 

package com.cobra.appactiviti.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.concurrent.Future;

/**
 * @author: yaobin
 * @date: 2019/8/3
 * @description:
 */
@Component
@Slf4j
public class SecondAsyncTask {

    @Async("1")
    public Future doTask1() throws InterruptedException {

        Long time1 = System.currentTimeMillis();
        Thread.sleep(3000L);
        Long time2 = System.currentTimeMillis();
        log.info("doTask1耗时:{}",time2-time1);
        return new AsyncResult<>("Task1 accomplished!");
    }

    @Async("2")
    public Future doTask2() throws InterruptedException {

        Long time1 = System.currentTimeMillis();
        Thread.sleep(2000L);
        Long time2 = System.currentTimeMillis();
        log.info("doTask1耗时:{}",time2-time1);
        return new AsyncResult<>("Task2 accomplished!");
    }

}

 

package com.cobra.appactiviti.controller;

import com.cobra.appactiviti.task.AsyncTasks;
import com.cobra.appactiviti.task.SecondAsyncTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Future;

/**
 * @author: yaobin
 * @date: 2019/8/2
 * @description:
 */
@RestController
@RequestMapping("/async")
public class TaskController {


    @Autowired
    private AsyncTasks asyncTasks;

    @Autowired
    private SecondAsyncTask secondAsyncTask;


    @GetMapping("/test")
    public String doTask() throws InterruptedException {

        Long time1 = System.currentTimeMillis();

        Future future1 = asyncTasks.doTaskOne();
        Future future2 = asyncTasks.doTaskTwo();
        Future future3 = asyncTasks.doTaskThree();

        while (true) {
            if(future1.isDone() && future2.isDone() && future3.isDone()) {
                // 三个任务都调用完成,退出循环等待
                break;
            }
        }

        Long time2 = System.currentTimeMillis();

        System.out.println(time2-time1);

        Long count = time2 - time1;

        return count.toString();

    }

    @GetMapping("/test1")
    public String doTask1() throws InterruptedException {

        Long time1 = System.currentTimeMillis();

        Future future1 = secondAsyncTask.doTask1();
        Future future2 = secondAsyncTask.doTask2();


        while (true) {
            if(future1.isDone() && future2.isDone()) {
                // 三个任务都调用完成,退出循环等待
                break;
            }
        }

        Long time2 = System.currentTimeMillis();

        System.out.println(time2-time1);

        Long count = time2 - time1;

        return count.toString();

    }

}

 

package com.cobra.appactiviti;

import org.springframework.boot.SpringApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableAsync
public class AppActivitiApplication {

    public static void main(String[] args) {
        SpringApplication.run(AppActivitiApplication.class, args);
    }

}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值