Java set a callback from ExecutorService

前端 未结 4 879
一整个雨季
一整个雨季 2020-12-31 09:29

I have a fixedThreadPool that I am using to run a bunch of worker threads to achieve parallel execution of a task with many components.

When all threads have finishe

4条回答
  •  执笔经年
    2020-12-31 09:45

    You can add a callback for when a thread returns in Java 8+ using CompletableFuture as in the following, where t is the result of your long-running computation,

    CompletableFuture.supplyAsync(() -> {
        T t = new T();
        // do something
        return t;
    }).thenApply(t -> {
        // process t
    });
    

    If you want to use callbacks in just Java 7, you could do something like,

    int x = 10;
    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(x);
    Future result = fixedThreadPool.submit(() -> {
        // do calculation
        return T;
    });
    fixedThreadPool.submit(() -> {
        long minutesToWait = 5;
        T t = null;
        try {
            t = result.get(minutesToWait, TimeUnit.MINUTES);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            LOGGER.error(e);
        }
        if (t != null) {
            // process t
        }
    });
    

提交回复
热议问题