0

我需要对项目列表进行长时间计算(检查远程服务器上的状态),并且由于项目的数量可能很大(起初从 1 到 100.000),我认为最好拆分和线程他们。

这是我所做的:

// Retrieving list of items in the Database
Query<Platform> query = Ebean.createQuery(Platform.class, "WHERE disabled = false AND removed IS NULL");
query.order("created ASC");
Integer quantities = query.findRowCount();

int limit = (int) Math.ceil(quantities / 10.0);
PagingList<Platform> list = query.findPagingList(limit); // This will return a list of 10 pages, containing (quantities / 10) items

for (int i = 0; i < list.getPageSize(); i++) {
    CheckState task = new CheckState(list.getPage(i).getList());
    Thread worker = new Thread(task);

    // Start the thread, never call method run() direct
    worker.start();
}

和 CheckState 类:

public class CheckState implements Runnable {
    private List<Platform> platforms;

    public CheckState(List<Platform> platforms) {
        this.platforms = platforms;
    }

    @Override
    public void run() {
        // Do the verification for each platforms
        for (Platform platform : platforms) {
            platform.executeLongComputation()
        }
    }
}

我的想法是最好限制线程数,所以与其将结果拆分为每页 100 个项目,我更喜欢限制其中 n 个项目的页数。这样做,我知道每次调用原始方法我将始终拥有最多 10 个线程(我可以在将来或多或少地更改它以调整性能)。

但是我想知道这是否是一个很好的实现,是否可以正常工作。例如说远程服务器不会应答,而我里面有一个 1000 项的列表,这不会导致问题(外面需要更长的时间才能完成)吗?

4

1 回答 1

1

您不必Thread自己管理实例。Java 已经提供了一种以ExecutorService. 如果您想启动一个池并在Threads 再次可用时重新使用它们,请将 aExecutorServiceThread池一起使用。你可以用Executors.newFixedThreadPool(int). 您可能会对许多其他工厂方法感兴趣。

请记住,大量线程意味着大量上下文切换。测试您的环境以获得最佳配置。

于 2013-10-14T14:55:06.557 回答