首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >多线程/并行化for循环JAVA的每一项

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

Stack Overflow用户
提问于 2016-12-01 01:10:17
回答 3查看 2.6K关注 0票数 4

我试图让每个线程访问一个for循环项,而另一个线程访问下一个项。我想使用多个线程来完成这个任务,创建的多个线程的数量将由用户输入。我使用executorservice和streams完成了这一工作。我想用简单的线程来做这件事。下面的内容正确吗?有更好的办法吗?

代码语言:javascript
复制
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);
}

另外,是否可能有一个线程不返回到以前的项,因为以前的线程已经计算了这个值?任何帮助都将不胜感激。谢谢

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-12-01 02:11:38

这是一个解决你的问题的方法。这将解析线程名以提供索引,并使用最终数组处理将数据传递到线程中。

代码语言:javascript
复制
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);
}
票数 2
EN

Stack Overflow用户

发布于 2016-12-01 02:28:24

它可以通过paralledStream通过AbacusUtil来实现。

代码语言:javascript
复制
final Pattern p = Pattern.compile("not");

Stream.of(fileMap).parallel(threadNum).map(entry -> {
    Matcher m = p.matcher(entry.getValue());
    int count = 0;
    while (m.find()) {
        count++;
    }
    return Pair.of(entry.getKey(), count);
}).forEach(entry -> {
    N.println("File Name: " + entry.getKey() + ", Count: " + entry.getValue());
});

如果您想学习如何自己编写多线程代码。下面是一个简单的示例:

代码语言:javascript
复制
final int threadNum = 3;
final ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
final Iterator<Entry<String, String>> iter = fileMap.entrySet().iterator();

for (int i = 0; i < threadNum; i++) {
    executorService.execute(new Runnable() {
        @Override
        public void run() {
            Entry<String, String> entry = null;
            while (true) {
                synchronized (iter) {
                    if (iter.hasNext() == false) {
                        break;
                    }
                    entry = iter.next();
                }

                final Matcher m = p.matcher(entry.getValue());
                int count = 0;
                while (m.find()) {
                    count++;
                }

                System.out.println("File Name: " + entry.getKey() + ", Count: " + count + ", thread: " + Thread.currentThread().getName());
            }
        }
    });
}

声明:我是AbacusUtil的开发人员。

票数 1
EN

Stack Overflow用户

发布于 2016-12-01 03:31:15

使用遍历数组的原始线程并行循环的标准方法如下所示,使用您的问题。

代码语言:javascript
复制
import java.util.*;
import java.util.regex.*;

public class MyClass {

public static void main(String[] args) {
    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.");
    String[] keys = fileMap.keySet().toArray(new String[fileMap.size()]);

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

    private static class MyRunnable implements Runnable {
        private Map<String, String> fileMap;
        private String[] keys;
        private int threadID;
        private int threadCount;
        Pattern p = Pattern.compile("not");
        public MyRunnable(Map<String, String> fileMap, String[] keys, int threadID, int threadCount) {
            this.fileMap = fileMap;
            this.keys = keys;
            this.threadID = threadID;
            this.threadCount = threadCount;
        }
        public void run(){
            for (int i=threadID; i<keys.length; i+= threadCount) {
                int counter = 0;
                Matcher m = p.matcher(fileMap.get(keys[i]));
                while (m.find()) {
                    counter++;
                }
                synchronized(MyClass.class){
                    System.out.println("File Name: " + keys[i]);
                    System.out.println("Count: " + counter);
                    System.out.println("ThreadID: " + threadID);
                }
            }
        }    
    }
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40901017

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档