一:单线程
1.在某方法里需要调用异步方法
new Thread(() -> {
// 业务
}).start();
2.整个方法都是异常
在方法头加注解
@Async
@Override
public void test(){
}
3.TaskExecutor
@Autowired
private TaskExecutor taskExecutor;
taskExecutor.execute(
new Runnable() {
@Override
public void run() {
try {
//业务
} catch (Exception e) {
e.printStackTrace();
}
}
}
);
二:线程池
public static ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(10);
// 延迟15分钟
pool.schedule( () -> {
// 业务
}, 15, TimeUnit.MINUTES
);
三:线程返回
// 此处演示多个异步线程统一等返回结果
List<Future<Boolean>> futures = new ArrayList<>();
for (int i=0;i<10;i++) {
// 分线程去执行-执行10次addRelation方法
Future<Boolean> future = addRelation(i);
futures.add(future);
}
//获取任务执行结果
boolean ok = true; // 最终结果(默认是成功,如果10次有一次或一次以上为false都是失败)
if (futures.size() > 0) {
try {
while (true) {
int i = 0;
for (Future<Boolean> future : futures) {
if (future.isDone()) {
++i;
boolean isOK = future.get(); // future.get() 是返回值,可以定义其他类型
if (!isOK) ok = false;
}
}
if (i == futures.size()) {
break;
}
}
} catch (Exception e) {
ok = false;
}
}