当前位置: 代码迷 >> java >> 从可调用接口将参数传递给函数调用
  详细解决方案

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

热度:11   发布时间:2023-07-31 10:57:46.0

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

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

我当前的班级看起来像这样:

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输出,因此我看不到需要使用它。

  相关解决方案