@Async prevent a thread to continue until other thread have finished

前端 未结 2 1222
我在风中等你
我在风中等你 2021-02-01 09:47

I have an application where for a certain number of times something needs to be calculated. This calculation function has the annotation @Async (from the Spring Framework), that

2条回答
  •  北荒
    北荒 (楼主)
    2021-02-01 10:25

    If you need to wait for the executions to finish, then you can return a Future as a return value, e.g.

    @Async
    public Future executeBla() {
        System.out.println("Bla!");
        return new AsyncResult(null);
    }
    

    This is slightly artificial, since there's no actual value being returned, but it will still allow the calling code to wait for all executions to finish:

    public void executeBlaALotOfTimes() {
        long before = System.currentTimeMillis();
    
        Collection> futures = new ArrayList>();
    
        for (int i = 0; i<40000; i++) {
            futures.add(executeBla());
        }
    
        for (Future future : futures) {
            future.get();
        }
    
        long after = System.currentTimeMillis(); 
    
        System.out.println("Time it took for a lot of bla to execute: " + (after - before) / 1000.0 + " seconds.");
    }
    

    Here, the first loop fires off the async tasks and stores the futures in a list. The seconds loop then iterates over the futures, waiting for each one to finish.

提交回复
热议问题