gpt4 book ai didi

java - 多线程/并行化for循环JAVA的每一项

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:36:49 24 4
gpt4 key购买 nike

我试图让每个线程访问 for 循环的单个项目,而另一个线程访问下一个项目。我想使用多个线程来执行此操作,并且创建的多个线程数将由用户输入。我已经使用 executorservice 和 streams 完成了这项工作。我想用简单的线程来做到这一点。以下正确吗?有没有更好的办法?

Map<String, String> fileMap = new HashMap<>();
fileMap.put("Age", "Age is not remotely associated with it.");
fileMap.put("Gender", "Gender plays a role but not that important.");
fileMap.put("Money", "People do not believe but this is the only factor that matters.");

Runnable myRunnable = new Runnable(){
public void run(){
for (Map.Entry<String, String> entry : fileMap.entrySet()) {
synchronized(this){
int counter = 0;
Pattern p = Pattern.compile("not");
Matcher m = p.matcher(entry.getValue());
while (m.find()) {
counter++;
}
System.out.println("File Name: " + entry.getKey());
System.out.println("Count: " + counter);
System.out.println(Thread.currentThread().getName());
}
}
}
};

int n = Integer.parseInt(args[0]);
for (int x=0; x<n; x++)
{
Thread temp= new Thread(myRunnable, "Thread #" + x);
temp.start();
System.out.println("Started Thread:" + x);
}

此外,是否可以让一个线程不返回到前一个项目,因为前一个线程已经计算了该值?任何帮助,将不胜感激。谢谢

最佳答案

这是您的问题的解决方案。这会解析线程名称以提供索引并使用最终数组来处理将数据传递到线程中。

Map<String, String> fileMap = new HashMap<>();
fileMap.put("Age", "Age is not remotely associated with it.");
fileMap.put("Gender", "Gender plays a role but not that important.");
fileMap.put("Money", "People do not believe but this is the only factor that matters.");


final int[] tgSize = new int[]{0};
final Map.Entry[][] entryArr = new Map.Entry[1][];

Runnable myRunnable = new Runnable(){
public void run(){
Integer index = Integer.valueOf(Thread.currentThread().getName().substring(8));

for(int i = index; i < fileMap.size(); i += tgSize[0]) {
int counter = 0;
@SuppressWarnings("unchecked")
Map.Entry<String, String> entry = entryArr[0][i];
Pattern p = Pattern.compile("not");
Matcher m = p.matcher(entry.getValue());
while (m.find()) {
counter++;
}
synchronized(this) {
System.out.println("File Name: " + entry.getKey());
System.out.println("Count: " + counter);
System.out.println(Thread.currentThread().getName());
}
}
}
};

int n = Integer.parseInt(args[0]);

tgSize[0] = n < fileMap.size() ? n : fileMap.size();
entryArr[0] = fileMap.entrySet().toArray(new Map.Entry[fileMap.size()]);


for (int x=0; x<n && x < fileMap.size(); x++)
{
Thread temp= new Thread(myRunnable, "Thread #" + x);
temp.start();
System.out.println("Started Thread:" + x);
}

关于java - 多线程/并行化for循环JAVA的每一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40901017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com