线程工作结果是意外的-Java

时间:2018-10-29 20:31:43

标签: java multithreading concurrency

我是多线程新手。 我正在开发一个程序,将具有许多记录(300万个整数)的文件读入某个链接列表,然后一些线程在每个列表上工作并计算列表的总和,以找到最大值和最小值。然后主线程会比较子线程的结果并显示最终结果。

程序使用此命令:

  

计算-f文件路径-t线程数

现在的问题是,当我使用一个线程运行该程序时,它所花费的时间少于某些线程。

我的CPU是i7核心。

这是一些时间的结果:

(线程数:持续时间)->(1:16),(2,3:32),(4,5,6,7:47),(8,9:31)...(17, 18,19,20:16)

该项目有2个项目:

工人阶级:

public class Worker implements Runnable {

    private List<Integer> records;
    private long[] res;
    private String name;

    Worker(String name, LinkedList<Integer> list, long[] res) {
        this.records = list;
        this.res = res;
        this.name = name;
    }

    @Override
    public void run() {

        long startTime = System.currentTimeMillis();
        long sum = 0;
        int max, min;

        if (records != null && records.size() > 0) {
            max = min = records.get(0);

            for (Integer num : records) {
                sum += num;
                if (num > max)
                    max = num;
                if (num < min)
                    min = num;
            }

            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;

            res[0] = sum;
            res[1] = max;
            res[2] = min;
            res[3] = duration;

            System.out.println(name + "\t->\ttime:\t" + duration + "\t, Records:\t" + records.size());
        }
    }
}

主类:

public class Main {

    public static void main(String[] args) {
        //read command and get inputs:
        System.out.println("Welcome to my app : ");

        while (true) {

            Scanner scanner = new Scanner(System.in);
            String command = scanner.nextLine().trim();
            if (command.startsWith("compute")) {
                command = command.substring("compute".length() + 1);
                args = command.split(" ");
            } else {
                System.out.println("wrong command.. this app only support 'compute'");
                exit(1);
            }

            Map<String, String> map = new HashMap<>(); //-p processes , -f filepath
            for (int i = 0; i < args.length - 1; i += 2)
                map.put(args[i], args[i + 1]);

            File txtFile = new File(map.get("-f").trim());
            final int threadCount = Integer.parseInt(map.get("-t").trim());

            ArrayList<LinkedList<Integer>> lists = readFile(txtFile, threadCount);
            if (lists == null) {
                System.out.println("Error: can not found txt file..");
                exit(2);
            }

            long[][] results = new long[threadCount][4];
            Thread[] thread = new Thread[threadCount];

            for (int i = 0; i < threadCount; i++) {
                thread[i] = new Thread(new Worker("thread " + (i + 1) ,lists.get(i), results[i]));
                thread[i].start();
            }

            boolean isAlive = true;
            while (isAlive) {
                isAlive = false;
                for (int i = 0; i < threadCount; i++)
                    isAlive |= thread[i].isAlive();
            }

            long[] res = null;
            for (long[] result : results) {
                if (res != null) {
                    res[0] += result[0];
                    if (res[1] < result[1])
                        res[1] = result[1];
                    if (res[2] > result[2])
                        res[2] = result[2];
                    if (res[3] < result[3])
                        res[3] = result[3];
                } else {
                    res = result;
                }
            }

            if (res != null) {
                System.out.println("sum : " + res[0]);
                System.out.println("max : " + res[1]);
                System.out.println("min : " + res[2]);
                System.out.println("duration : " + res[3]);
            }

        }
    }

    private static ArrayList<LinkedList<Integer>> readFile(File txtFile, int procCount) {
        if(!txtFile.exists() || txtFile.isDirectory())
            return null;

        ArrayList<LinkedList<Integer>> arrayList = new ArrayList<>();

        for(int i = 0; i < procCount; i++)
            arrayList.add(new LinkedList<>());

        try {
            int index = 0;
            BufferedReader bufferedReader = new BufferedReader(new FileReader(txtFile));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                arrayList.get(index).add(Integer.parseInt(line));
                index++;
                if(index == procCount)
                    index = 0;
            }

            return arrayList;
        }   catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }
}

3 个答案:

答案 0 :(得分:0)

为什么不使用执行器

使用 argument Integer.parseInt(map.get(“-t”)。trim())创建线程池。并且不再需要isAlive。而结果未来的概念。

Threads Pool

Future

Executors - Threads Control

Examples

答案 1 :(得分:0)

我认为,要学习多线程,了解阿姆达尔定律很重要。阿姆达尔定律可用于计算通过并行运行一部分计算可加速的计算量。我不想过多地讨论技术细节,因此您可以在Wikipedia上阅读:https://en.wikipedia.org/wiki/Amdahl%27s_law

阿姆达尔定律基本上说并发计算的速度与线程数不是线性的,线程数取决于处理器中内核的数量(除非您的代码进行网络,IO等)。因此,当线程数量加倍时,您不能指望程序将其速度提高一倍。

此外,与Java中的任何其他类一样,线程类也需要大量创建开销,并且会占用大量资源。因此,创建更多线程而没有有效地仅平衡算术运算(JVM已经对其进行了非常优化)的输入,将使程序的速度变得不可预测,甚至变得更慢。

还有更多需要考虑的问题。有一点建议是使用Java的类ExecutorService来管理线程。编码愉快。

答案 2 :(得分:0)

您“与众不同”的结果很可能与JIT compiler完成的优化有关

您的代码在这里正在执行“某种基准测试”,具有可配置的线程数。 对于此类基准,建议使用JMH framework

如果您只是在学习多线程,建议您不要评估代码的性能。进行基准测试时,有很多事情需要考虑,如果做不正确会导致意外的结果,例如您现在看到的结果。

相关问题