go语言异步与Java异步,比较

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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值