使用Spring轻松实现Fork-Join

头两天我老弟问我Fork-Join是怎么个情况,我就简单说了一下。我顺便提了一下,Spring里面@Async会很智能的封装好调用函数然后扔给线程池,你要做的就是简单配置一下线程池。

下面是示例代码,这里只给出代码和结果:

第一种情况,Service类:

@Async
public String test1() {
    String threadName = Thread.currentThread().getName();
    log.error("{}: 1 start", threadName);
    try {
        Thread.sleep(5000L);
    } catch (Exception e){
    }
    log.error("{}: 1 end", threadName);
    return "s1";
}

@Async
public String test2() {
    String threadName = Thread.currentThread().getName();
    log.error("{}: 2 start", threadName);
    try {
        Thread.sleep(2000L);
    } catch (Exception e){
    }
    log.error("{}: 2 end", threadName);
    return "s2";
}

Controller类:

try {
    String threadName = Thread.currentThread().getName();
    log.error("{}: 0 start", threadName);
    PrintWriter out = response.getWriter();
    String f1 = testService.test1();
    String f2 = testService.test2();
    log.error("{}: 0 end {} {}", threadName, f1, f2);

} catch (Exception e) {
}

 

结果是,test1和test2在不同线程被执行,然而对test1和test2的调用,立刻结束,f1和f2都是null。

也就是说,这样可以独立执行两个后台任务,然而并不能等待返回结果,怎样才能得到结果呢?

 

第二种情况,Service类:

@Async
public Future<String> test1() {
    String threadName = Thread.currentThread().getName();
    log.error("{}: 1 start", threadName);
    try {
        Thread.sleep(5000L);
    } catch (Exception e){
    }
    log.error("{}: 1 end", threadName);
    return new AsyncResult<>("s1");
}

@Async
public Future<String> test2() {
    String threadName = Thread.currentThread().getName();
    log.error("{}: 2 start", threadName);
    try {
        Thread.sleep(2000L);
    } catch (Exception e){
    }
    log.error("{}: 2 end", threadName);
    return new AsyncResult<>("s2");
}

 

Controller类:

try {
    String threadName = Thread.currentThread().getName();
    log.error("{}: 0 start", threadName);
    PrintWriter out = response.getWriter();
    Future<String> f1 = testService.test1();
    Future<String> f2 = testService.test2();
    
    log.error("{}: 0 end {} {}", threadName, f1.get(), f2.get());
} catch (Exception e) {
}

 

这样可以正确得到结果。总之就是,Futrue<T>和AsyncResult<T>让调用线程可以join,等待Future结果。

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值