Java线程(初学者)

时间:2018-05-12 21:27:38

标签: java

我在这里处理我的java代码时遇到了问题。

我确信我已经使用过我在网上创建的推荐。但它仍然无效。

import java.util.*;
import java.util.concurrent.*;
import java.util.Map;

public class GradeCounterImpl implements GradeCounter {

    ConcurrentHashMap<String, GradeCount> save;

    public GradeCount[] count(String[] grades, int nThreads) {
        if (grades == null) {
            return new GradeCount[0];
        }
        if (grades.length == 0) {
            return new GradeCount[0];
        }

        save = new ConcurrentHashMap<>();

        class WorkUnit implements Runnable {
            final String[] positions;

            public WorkUnit(String[] i) {
                this.positions = i;
            }

            public void run() {
                for (String pos : positions)
                    if (pos != null) {
                        if (save.containsKey(pos)) {
                            save.get(pos).count++;
                        } else {
                            save.put(pos, new GradeCount(pos, 1));
                        }
                    }
            }
        }

        int divide = (grades.length / nThreads);
        ExecutorService exe = Executors.newFixedThreadPool(nThreads);

        for (int i = 0; i < nThreads; i++)
            exe.execute(new WorkUnit(arrayBetween(i * divide, (i + 1) * divide, grades)));

        exe.shutdown();

        try {
            exe.awaitTermination(30, TimeUnit.MINUTES);
        } catch (InterruptedException error) {
            error.printStackTrace();
        }

        Collection<GradeCount> c = save.values();
        return c.toArray(new GradeCount[c.size()]);
    }

    private String[] arrayBetween(int start, int end, String[] target) {
        String[] ans = new String[end - start];
        for (int i = start; i < end; i++)
            if (i < target.length)
                ans[i - start] = target[i];
        return ans;
    }
}


public class GradeCount implements Comparable<GradeCount> {
    public String grade;
    public int count;

    public GradeCount(final String grade, final int count) {
        this.grade = grade;
        this.count = count;
    }

    public int compareTo(final GradeCount other) {
        final int gradeCmp = this.grade.compareTo(other.grade);
        return gradeCmp == 0 ? Integer.compare(this.count, other.count) : gradeCmp;
    }
}

该怎么办?

代码必须计算grade数组中出现的每个String,并将结果保存在hashmap中,然后返回它们的值。

有什么问题?

代码不是(因为你可以使用标题的客人)不能正常工作。它不算数,我在大数组测试之间有很大的不同。

观察:

当我使用小数组(0 - 50值)进行测试时,程序运行良好

现在:我该怎么办?

感谢您在这里阅读所有内容,希望您能帮助我。

1 个答案:

答案 0 :(得分:2)

问题在于:

                    if (save.containsKey(pos)) {
                        save.get(pos).count++;
                    } else {
                        save.put(pos, new GradeCount(pos, 1));
                    }

您有一个ConcurrentHashMap,但您的GradeCounter未同步,因此对count++的调用无法更正

我认为您的GradeCount看起来像{grade, count}所以我建议你使用Map<String, AtomicInteger> isntead