本文介绍了一起运行多个线程池(ExecutorService)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,需要通过4个场景来运行.我想在2个线程之间拆分(这样我就可以发送到其他服务器)我已经在2台服务器上使用了此功能,但是在尝试清理代码时,我创建了如下所示的内容:

I have an object that I need to run through 4 scenarios. I want to split this between 2 threads (so I can send to an additional server)I got this working to the 2 servers, but in trying to clean up the code i have created what looks like this;

 ExecutorService executor1 = Executors.newFixedThreadPool(1);
 ExecutorService executor2 = Executors.newFixedThreadPool(1);

 executor1.execute(userProvisioner1);
 executor1.execute(userProvisioner2);
 executor2.execute(userProvisioner3);
 executor2.execute(userProvisioner4);

 executor1.shutdown();
 executor2.shutdown();

 while (!executor1.isTerminated()&!executor2.isTerminated()) {
 }

userProvisioner1& userProvisioner2需要顺序运行(与3和4一样),但可以彼此并排运行.

userProvisioner1 & userProvisioner2 need to be run sequentially (as do 3 & 4) but can be run along side each other.

这确实有效,但是自尝试同时使用2个池以来,我遇到了一些问题.这是泳池问题还是其他问题?

This does work, but I have hit issues since trying to use the 2 pools at once. Is this an issue with the pools or something else?

推荐答案

如果您需要顺序活动,则可以先调用一个任务,然后再调用另一个任务.您这种情况下的简单解决方案是这样的.

If you need sequential activity, you can call one task and then another. The simple solution in your case is something like this.

ExecutorService exec = Executors.newFixedThreadPool(2);

exec.execute(new Runnable() {
    public void run() {
        userProvisioner1.run();
        userProvisioner2.run();
    }
});
exec.execute(new Runnable() {
    public void run() {
        userProvisioner3.run();
        userProvisioner4.run();
    }
});

exec.shutdown();
exec.awaitTermination();

这篇关于一起运行多个线程池(ExecutorService)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-01 01:03