springboot异步执行

  1. 创建springboot项目
  2. 调用多线程controller
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @Controller
    public class AsyncController {
    
    	@Autowired
    	private User2Service user2Service;
    	
    	@GetMapping("/async")
    	@ResponseBody
    	public Object async(){
    		System.out.println("步骤------1");
    		user2Service.index();
    		System.out.println("步骤------2");
    		return "success";
    	}
    }
  3. 创建执行多线程方法
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.stereotype.Component;
    
    @Component
    public class User2Service {
    
    	@Async  // 多线程执行
    	public void index(){
    		System.out.println("步骤------3");
    		for (int i = 0; i < 10; i++) {
    			try {
    				Thread.sleep(1000);
    			} catch (InterruptedException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    			System.out.println(+i);
    		}
    		System.out.println("步骤------4");
    	}
    	
    }
  4. 开启多线程注解

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cache.annotation.EnableCaching;
    import org.springframework.scheduling.annotation.EnableAsync;
    import org.springframework.scheduling.annotation.EnableScheduling;
    
    @SpringBootApplication
    @EnableCaching // 开启缓存注解
    //@EnableScheduling // 开启定时任务
    @EnableAsync  // 开启异步注解
    public class App {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		SpringApplication.run(App.class, args);
    	}
    
    }
  5. 启动

  6. 打印的执行步骤是1-2-3-4    其主线程的执行优先级高,

  7. 去掉异步注解在执行的步骤是1-3-4-2    都是主线程在跑

猜你喜欢

转载自blog.csdn.net/xiaobo5264063/article/details/89667503
今日推荐