简体   繁体   English

hashmap 入口循环中的多线程 - 执行器服务 (Java)

[英]Multithreading in a hashmap entry loop - Executor service (Java)

I have a map (HashMap<String, Map<String,String> mapTest) in which I have a loop that does several operations.我有一个 map (HashMap<String, Map<String,String> mapTest),其中我有一个执行多个操作的循环。

HashMap<String, Map<String,String> mapTest = new HashMap<>();
ArrayList<Object> testFinals = new ArrayList<>();

for (Map.Entry<String, Map<String, String>> entry: mapTest.entrySet()) {

// in here I do a lot of things, like another for loops, if's, etc.

//the final juice to get from here is that in each time the loop is executed I have this:

List<Object> resultExp = methodXYZ(String, String, String);

testFinals.addAll(resultExp);

}

- In here, I have to wait before I proceed, since I need the full testFinals filled to advance. - 在这里,我必须等待才能继续,因为我需要填写完整的 testFinals 才能晋级。

Now, what I need to do is:现在,我需要做的是:

1 - This mapTest can have like 400 rows to iterate from. 1 - 这个 mapTest 可以有 400 行进行迭代。

I want to schedule like 4 threads, and assign like 100 rows of that FOR cycle to thread 1, the next 100 rows of the mapTest to thread 2, and so on.我想安排 4 个线程,并将该 FOR 循环的 100 行分配给线程 1,将 mapTest 的下 100 行分配给线程 2,依此类推。

Already tryed a few solutions, like this one:已经尝试了一些解决方案,比如这个:

ExecutorService taskExecutor = Executors.newFixedThreadPool(4);

while(...) {

  taskExecutor.execute(new MyTask());

}

taskExecutor.shutdown();

try {

  taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

} catch (InterruptedException e) {

  ...

}

but I can't adapt this correctly or a similar working solution to what I have now, with that map iteration.但是我无法通过 map 迭代正确地调整这个或类似的工作解决方案。

When using concurrent, consider that the threads must obtain, hold and relinquish locks on a variable.使用并发时,请考虑线程必须获取、持有和放弃对变量的锁定。

This is done at field level -not content.这是在字段级别完成的 - 而不是内容。

On short... The hasmap is locked for access ya specific thread.简而言之... hasmap 被锁定以访问特定线程。 Not some random entry.不是一些随机进入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM