@SpringBootApplication
//開啓線程的註解
@EnableAsync
public class PushServiceApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(PushServiceApplication.class).run(args);
}
}
之後建立一個類
package com.seckill.main.controller;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class AsyncTask {
@Async
public void test2( ) throws InterruptedException{
long start = System.currentTimeMillis();
Thread.sleep(1000);
long end = System.currentTimeMillis();
System.out.println("test2");
}
@Async
public void test3() throws InterruptedException{
long start = System.currentTimeMillis();
Thread.sleep(3000);
long end = System.currentTimeMillis();
System.out.println("test3");
}
}
之後是調用測試
@Autowired
private AsyncTask asyncTask;
@RequestMapping(value={"/test"})
@ResponseBody
public Object asyncTasktest() throws InterruptedException{
int i=0;
while(true) {
if(i>50){
break;
}
asyncTask.test2();
asyncTask.test3();
i++;
System.out.println(i);
}
System.out.println("結束");
return "1";
}
//總結 在方法上面不能定義成static 靜態的,不然就不會有異步的效果,第二就是不能有返回值,有的話,會報錯,一般就是給void 如定義一個方法: