java spring boot 异步方法@Async

java spring boot 异步方法@Async

ps:我这里要说明下 这个异步是多线程 所以要考虑线程安全 变量共享的问题

1 首先开启类 

@EnableAsync //开启异步调用



2 直接方法前面加
@Async 就可以异步了
package com.example.demo2122;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;

import java.util.*;
import java.util.stream.IntStream;

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

@RestController
@Component
public class HelloControl {

    @GetMapping("/hello")
    public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
        System.out.println("####IndexController####   1");
        this.sendSms();
        System.out.println("####IndexController####   3");
        return "success";
    }



    @Async
    public void sendSms(){
        Timer timer = new Timer();
        timer.schedule(new RemindTask(), 3*1000);
    }

}
class RemindTask extends TimerTask {
    public void run() {
        System.out.println("3秒后执行sendSms");

    }
}

猜你喜欢

转载自www.cnblogs.com/newmiracle/p/12750788.html