我想让每个线程访问for循环的单个项目,而另一个线程访问下一个项目。我想要使用多个线程来完成此操作,并且创建的多个线程的数量将由用户输入。我已经使用executorservice和流来完成此操作。我想用简单的线程来做到这一点。以下是否正确?有没有更好的办法?多线程/并行for循环JAVA的每个项目
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);
}
此外,是否有可能有一个线程不会返回到前一个项目,因为上一个线程已经计算出的值? 任何帮助,将不胜感激。谢谢
似乎毫无意义的有线程,然后尝试阻止它由于'synchronized'运行。虽然在这种情况下这是什么?如果你想阻止它重新处理已经找到的行,那么可以从'map'中删除它。 –
我不清楚你是什么意思的简单线程。 Java线程没有索引(比如你在OpenCL/Cuda中看到的),所以如果你想给它们索引,你需要扩展线程的功能,尽管你的可运行COULD可以保存索引。由于您创建的线程数量并不总是与正在处理的项目数量相匹配,因此您在此应用程序中的逻辑也存在缺陷。最小我会改变你的for循环从'x
@RalphRitoch请原谅我的英语。我的意思是'使用简单的线程来做这件事',而不是通过ExecutorService或任何其他包。只是线程,也许地图/ ConcurrentHashMaps – Tao