使用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结果。

猜你喜欢

转载自flashing.iteye.com/blog/2319313
今日推荐