随笔 springboot @Async注解

在springboot中使用异步线程,需使用@Async注解。

在启动类上需增加@EnableAsync(proxyTargetClass = true),proxyTargetClass为选择何种代理,

@SpringBootApplication
@EnableAsync(proxyTargetClass = true)
public class ChuanApplication {

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

}

controller:

@RestController
@RequestMapping("test")
public class AsyncController {
    @Autowired
    public AsyncTest asyncTest;

    @RequestMapping(value = "testAsync",method = RequestMethod.GET)
    public void testAsync(){
        System.out.println("当前时间:"+LocalTime.now());
        List> list =new ArrayList<>();
        try {
            asyncTest.threadTest1();
            Future  future2= asyncTest.threadTest2();
            list.add(future2);
            Future  future3 =asyncTest.threadTest3();
            list.add(future3);
            Thread.sleep(1000);
            System.out.println("执行阻塞!");
            list.stream().forEach(future-> {
                try {
                    System.out.println(future.get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            });
        }catch (Exception e){
         e.printStackTrace();
        }
        System.out.println("结束时间:"+LocalTime.now());
    }
}

service:

@Service
public class AsyncTest {

    @Async
    public void threadTest1(){
        System.out.println("当前线程名:"+Thread.currentThread().getName());
       try{
           Thread.sleep(5000);
           System.out.println("线程:"+Thread.currentThread().getName()+"执行结束,时间为:"+ LocalTime.now());
       }catch (Exception e){
           e.printStackTrace();
       }
    }
    @Async
    public Future threadTest2(){
        System.out.println("当前线程名:"+Thread.currentThread().getName());
        try{
            Thread.sleep(3000);
            System.out.println("线程:"+Thread.currentThread().getName()+"执行结束,时间为:"+ LocalTime.now());

        }catch (Exception e){
            e.printStackTrace();
        }
        return new AsyncResult<>("成功!"+Thread.currentThread().getName());
    }
    @Async
    public Future threadTest3(){
        System.out.println("当前线程名:"+Thread.currentThread().getName());
        try{
            Thread.sleep(4000);
            System.out.println("线程:"+Thread.currentThread().getName()+"执行结束,时间为:"+ LocalTime.now());
        }catch (Exception e){
            e.printStackTrace();
        }
        return new AsyncResult<>("成功!"+Thread.currentThread().getName());
    }
}

运行结果:

当前时间:18:18:25.625
当前线程名:task-3
当前线程名:task-4
当前线程名:task-5
执行阻塞!
线程:task-4执行结束,时间为:18:18:28.638
成功!task-4
线程:task-5执行结束,时间为:18:18:29.638
成功!task-5
结束时间:18:18:29.638
线程:task-3执行结束,时间为:18:18:30.638

在这里进行一个实验,将threadTest2()和threadTest3()进行阻塞,阻塞是通过future.get()方法实现。threadTest1()则不进行阻塞。

如果异步返回,需返回Future,return为AsyncResult

 

你可能感兴趣的:(springboot,多线程)