?Main.java
package org.example;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
public class Main {
/*** 逻辑线程 */
static public ExecutorService logicThread = Executors.newSingleThreadExecutor();
/*** IO线程 */
static public ExecutorService[] ioThreadArray = new ExecutorService[Runtime.getRuntime().availableProcessors()];
/*** 初始化 */
static {
for (int i = 0; i < ioThreadArray.length; i++) {
ioThreadArray[i] = Executors.newSingleThreadExecutor();
}
}
static public void main(String[] args) {
// 在这里设置想要的任何结果类型
AtomicReference<Integer> num = new AtomicReference<>();
asyncProcess(
123,
() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (Exception e) {
e.printStackTrace();
}
num.set(12345);
},
() -> {
Integer ret = num.get();
System.out.println("ret=" + ret + " " + Thread.currentThread().getName());
}
);
}
/**
* 封装异步操作
*
* @param hashId
* @param async
* @param finish
*/
static public void asyncProcess(Object hashId, IDoAsync async, IDoFinish finish) {
int index = Math.abs(hashId.hashCode() % ioThreadArray.length);
ioThreadArray[index].submit(() -> {
// 在IO线程中执行耗时操作
safeRun(async::doAsync);
// 将最终结果提交到业务线程
logicThread.submit(() -> safeRun(finish::doFinish));
});
}
static void safeRun(Runnable run) {
try {
run.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}
IDoAsync.java
package org.example;
@FunctionalInterface
public interface IDoAsync {
void doAsync();
}
IDoFinish.java
package org.example;
@FunctionalInterface
public interface IDoFinish {
void doFinish();
}
总结:
这样子在异步操作中跨线程操作同一个对象,就可以用这个,避免final之类的提示错误。
|