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

时间:2019-02-12 12:10:16

标签: java threadpoolexecutor

我正在尝试构建实用程序库,该实用程序库将任务添加到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的对象并遍历其任务列表并传递各个可调用函数。我想为客户抽象。

1 个答案:

答案 0 :(得分:0)

您是否考虑过Go to Services manager(services.msc) and enable the below services and try again. 包裹中的任何东西。我认为它比java.util.function更适合您的用例,例如CallableBiConsumer。 由于示例代码中未使用BiFunction输出,因此我看不到需要使用它。