ExecutorService executorService = Executors.newCachedThreadPool();
//线程一
executorService.submit(new Callable<String>() {
@Override
public String call() throws Exception {
for (int i = 0; i < 100; i++) {
Thread.sleep(1000);
System.out.println("Thread1"+i);
}
return null;
}
});
//线程二
executorService.submit(new Callable<String>() {
@Override
public String call() throws Exception {
for (int i = 0; i < 100; i++) {
Thread.sleep(1000);
System.out.println("Thread2"+i);
}
return null;
}
});
}
@EnableDiscoveryClient
@SpringBootApplication
@EnableAsync//启动类添加注解开启异步
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class, args);
}
}
@Async可以加在类上也可以加在方法上,加在类上对所有方法生效,加在方法上对方法生效(需被spring管理)
@Service
public class AsyncServiceImpl {
@Async
public void asyncMethod(String str) throws InterruptedException {
for (int i = 0; i < 10; i++) {
Thread.sleep(1000);
System.out.println(str+i);
}
}
}
效果
@RestController
public class AsyncController {
@Autowired
AsyncServiceImpl asyncService;
@PostMapping("/asyncTest")
public void asyncTest(){
try {
asyncService.asyncMethod("线程一");
asyncService.asyncMethod("线程二");
} catch (InterruptedException e) {
e.printStackTrace();
}
return;
}
}
原文:https://www.cnblogs.com/xzh-hash/p/14833839.html