go语言异步与Java异步
一、概要
go语言异步,由于后来者居上,异步和异步处理都和容易。Java 异步相对比较臃肿一点,也不是太好控制。具体参考如下分析
二、golang异步
1) goroutine方式:
代码块
go func()
2) channel方式:
// 创建一个双向channel
ch := make(chan interface{})
interface{}表示chan可以为任何类型
channel有发送和接受两个主要操作。发送和接收两个操作都使用<-运算符
三、java异步
可以通过spring core包中ThreadPoolTaskExecutor,或JUC包中的ThreadPoolExecutor。
1) ThreadPoolTaskExecutor方式 。 细节参考: https://www.journaldev.com/20457/spring-async-annotation
Springboot启动类加入 EnableAsync注解,使能异步
代码块
@SpringBootApplication
@EnableAsyncEnableAsync
public class AsyncApp {
...
}
在具体的function上,标注异步注解。【此处有坑,看有的同学,使用的时候,没有把这个异步方法和业务类单独分开。 不是两个类那就是假异步,具体可以research一下】
代码块
@Async
public void asyncMethodWithVoidReturnType() {
System.out.println("Execute method asynchronously. "
+ Thread.currentThread().getName());
}
2) 线程池之ThreadPoolExecutor 。 细节参考: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html
代码块
Java
// 定义线程池
private static final ExecutorService EXECUTOR_INSTANCE = new ThreadPoolExecutor(5, 10, 5, TimeUnit.MINUTES,
new LinkedBlockingQueue<>(5),
new ThreadFactoryBuilder().setNameFormat("inteface-select-t-%d").build(),
(r, e) -> {
LOGGER.warn("获取接口串行执行一次:r={}", r);
if (!e.isShutdown()) {
r.run();
}
});
//执行callable方法
public Future<BitSet> submit(String groupMark, TracerInfo tracerInfo) {
return EXECUTOR_INSTANCE.submit(new MethodCallable(groupMark, tracerInfo));
}
代码块
Java
// 参数参考:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory)
Creates a new ThreadPoolExecutor with the given initial parameters and default rejected execution handler.
Parameters:
corePoolSize - the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
maximumPoolSize - the maximum number of threads to allow in the pool
keepAliveTime - when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating.
unit - the time unit for the keepAliveTime argument
workQueue - the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method.
threadFactory - the factory to use when the executor creates a new thread