将参数传递给可调用接口的函数调用

Pass Argument to a function call from callable interface

我正在尝试构建一个实用程序库,用于在 ThreadPoolExecutor 队列中添加任务。我想接受一个 list/array 个对象、一个可调用函数和一个要在可调用函数中传递的函数参数列表。现在我想在我从可调用接口进行的函数调用中传递这些列表或参数,但 Callable 接口只有一个不带任何参数的函数。

有人可以帮我重新设计结构吗?我希望这个库的客户使用上述参数调用一个函数,并且该库应该处理所有事情。

我当前的 class 看起来像这样:

public class ThreadPoolExecutorUtils {

    private ExecutorService executorService;

    /**
     * Initialize Executor service with given number of threads
     * @param threadCount : number of threads on the thread pool
     */
    public ThreadPoolExecutorUtils(int threadCount) {
        executorService = Executors.newFixedThreadPool(threadCount);
    }

    /**
     * Add the task to the queue of current threadpool executor
     * @param callableFunc: Function to be called from every thread
     */
    public <T> void scheduleTask(Callable<T> callableFunc) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    callableFunc.call();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    /**
     * Blocks until all tasks have completed execution after a shutdown
     * request, or the timeout occurs, or the current thread is
     * interrupted, whichever happens first.
     * @param timeOutSeconds : The maximum time in seconds to wait
     */
    public void awaitCompletion(int timeOutSeconds) {
        executorService.shutdown();
        try {
            executorService.awaitTermination(timeOutSeconds, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            executorService.shutdownNow();
        }
    }

}

在这种情况下,客户端必须创建 ThreadPoolExecutorUtils 的对象并遍历其任务列表并传递单独的可调用函数。我想为客户抽象它。

您是否考虑过 java.util.function 包中的任何内容。我认为它比 Callable 更适合您的用例,例如 BiConsumerBiFunction。 由于 Callable 输出未在您的示例代码中使用,因此我认为没有必要使用它。