并发多线程使用
使用场景:
- 事物操作后,与事物无关的操作比如操作日志
- 查询主表后开多线程查询多个子表
- 插入主表后,需要插入多个无关联的子表,此时需要做多线程的事物统一性。
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class AsyncTaskUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(AsyncTaskUtil.class);
private static Executor executor;
public AsyncTaskUtil() {
}
public static void runTask(AsyncTask asyncTask) throws RuntimeException {
if (asyncTask == null) {
throw new RuntimeException("async task is null");
} else {
CompletableFuture.runAsync(() -> {
Object returnValue = asyncTask.run();
asyncTask.callback(returnValue);
}).exceptionally((e) -> {
LOGGER.error("async task execute failed e={}", e);
return null;
});
}
}
public static Object[] runAll(List<AsyncTask> asyncTaskList) throws RuntimeException {
if (asyncTaskList != null && !asyncTaskList.isEmpty()) {
try {
int size = asyncTaskList.size();
Object[] returnValueList = new Object[size];
CompletableFuture<Void>[] array = new CompletableFuture[size];
int i = 0;
for(int n = asyncTaskList.size(); i < n; ++i) {
AsyncTask asyncTask = (AsyncTask)asyncTaskList.get(i);
CompletableFuture<Void> function = CompletableFuture.runAsync(() -> {
Object returnValue = asyncTask.run();
int index = asyncTask.getTaskNum();
returnValueList[index] = returnValue;
}, executor);
array[i] = function;
}
CompletableFuture.allOf(array).get();
return returnValueList;
} catch (Exception var9) {
LOGGER.error("async task execute failed e={}", var9);
return null;
}
} else {
throw new RuntimeException("async task is null");
}
}
public static void main(String[] args) {
AsyncTask task1 = new AsyncTask() {
public Object run() {
System.out.println(Thread.currentThread() + "---------");
return null;
}
};
AsyncTask task2 = new AsyncTask() {
public Object run() {
System.out.println(Thread.currentThread() + "==========");
return null;
}
};
List<AsyncTask> taskList = new ArrayList();
taskList.add(task1);
taskList.add(task2);
runAll(taskList);
}
static {
executor = new ThreadPoolExecutor(10, 20, 60L, TimeUnit.SECONDS, new SynchronousQueue());
}
}