【发布时间】:2016-12-01 01:10:17
【问题描述】:
我试图让每个线程访问单个项目的 for 循环,而另一个线程访问下一个项目。我想使用多个线程来执行此操作,并且创建的多个线程的数量将由用户输入。我已经使用 executorservice 和流完成了这项工作。我想使用简单的线程来做到这一点。下面是正确的吗?有没有更好的办法?
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而试图阻止它运行。虽然在这种情况下this是什么?如果您想阻止它重新处理已找到的行,则可以将其从map中删除 -
我不清楚你所说的简单线程是什么意思。 Java 线程没有索引(例如您在 OpenCL/Cuda 中看到的),因此如果您想为线程提供索引,则需要扩展线程的功能,尽管您的可运行对象可以保存索引。您在此应用程序中的逻辑也存在缺陷,因为您创建的线程数并不总是与您正在处理的项目数相匹配。至少我会将您的 for 循环从
x<n更改为x < n && x < fileMap.size() -
@RalphRitoch 请原谅我的英语。我的意思是“使用简单的线程来做到这一点”,而不是通过 ExecutorService 或任何其他包。只是线程以及 Maps/ConcurrentHashMaps
标签: java multithreading