Home > AI > Backend > SpringBoot >

@Async

Example

@SpringBootApplication
@EnableAsync
public class Demo12Application {

	public static void main(String[] args) {

		SpringApplication.run(Demo12Application.class, args);
	}
}






@Service
 class TaskServer {

    @Async
    public void doTaskA() throws InterruptedException {
        System.out.println("TaskA thread name->" + Thread.currentThread().getName());
        Long startTime = System.currentTimeMillis();
        TimeUnit.SECONDS.sleep(2);

        Long endTime = System.currentTimeMillis();
        System.out.println("TaskA time-consuming:" + (endTime- startTime));
    }

    @Async
    public void doTaskB() throws InterruptedException {
        System.out.println("TaskB thread name->" + Thread.currentThread().getName());
        Long startTime = System.currentTimeMillis();
        TimeUnit.SECONDS.sleep(2);
        Long endTime = System.currentTimeMillis();
        System.out.println("TaskB time-consuming:" + (endTime- startTime));
    }
}




@RestController
 class HelloController {

    @Autowired
    private TaskServer taskServer;

    @GetMapping("/async")
    public String testAsync() throws Exception {
        System.out.println("Main thread name -->" + Thread.currentThread().getName());
        taskServer.doTaskA();
        taskServer.doTaskB();
        return "Hello World";
    }
}

Leave a Reply