ThreadPoolExecutor:等待方法外的终止

时间:2015-08-07 06:28:53

标签: java multithreading threadpool threadpoolexecutor

当前情况: 我的代码(比如说“Class Caller:caller()”)将调用一个类的方法(类ThreadPoolClass:writeData()),它通过ThreadPoolExecutor在内部执行它的任务。现在,这个实现不会等待所有任务的终止。

问题: 虽然我的代码(方法调用者())需要等到这个(方法writeData())ThreadPoolExecutor的所有任务都完成。目前,控制器在提交任务后返回到caller()方法。

ThreadPoolClass的实现无法改变,这就是我想弄清楚如何实现这一目标的原因。

//示例代码

class Caller {
    public static void main(String[] args) {
        ThreadPoolClass t = new ThreadPoolClass();
        t.writeData();

        // I want to wait here until the execution is complete
    }
}

class ThreadPoolClass{
    void writeData() {
        Runnable thread = new Runnable() {

            @Override
            public void run() {
                //  Do some database commit operations

            }
        };
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1);
        fixedThreadPool.submit(thread);
        fixedThreadPool.shutdown();
    }
}

任何抬头都会有所帮助 - 即使是否有可能。

注意**这只是一个示例,我的原始代码有一系列类方法调用,最终使用ThreadPoolExecutor执行该方法。

由于 菜

1 个答案:

答案 0 :(得分:0)

感谢大家的投入。基于上述评论和我的一些分析,我也认为这是无法实现的。总结评论:

在没有更改ThreadPoolClass的代码的情况下我没有看到这种可能性,除了编写一个新的类做同样但有可能等待/阻塞或回调。 - Fildor

是否可以选择复制“执行某些数据库提交操作”并在主线程上按顺序执行它们?重用代码很棒,但API使其无法实现。