方法上使用@Async注解
@Component
public class Tasks{
//定義一個(gè)隨機(jī)對(duì)象.
public static Random random = new Random();
@Async
public void taskOne() throws InterruptedException{
System.out.println("開始做任務(wù)一");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("完成任務(wù)一,耗時(shí):" + (end - start) + "毫秒");
}
@Async
public void taskTwo() throws InterruptedException{
System.out.println("開始做任務(wù)二");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("完成任務(wù)二,耗時(shí):" + (end - start) + "毫秒");
}
@Async
public void taskThree() throws InterruptedException{
System.out.println("開始做任務(wù)三");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("完成任務(wù)三,耗時(shí):" + (end - start) + "毫秒");
}
}
啟動(dòng)上使用注解@EnableAsync