多线程比一个慢

时间:2014-10-15 21:00:03

标签: java multithreading performance semaphore

我正在使用多线程编写应用程序来计算txt文件中的char数。 文件包含10 000 000个字符。 10 000行和1 000列。

已编辑
关于问题的第一部分: Prevoius问题是关于线程的,我以错误的方式使用了thread.join();

第二部分: 你能帮我提高性能和安全性吗?这是我的代码(需要使用信号量):

public class MultiThread implements Runnable {

    HashMap<String, AtomicInteger> asciiMap = Maps.newHashMap();
    LinkedList<String> asciiLines = ReadDataFromFile.lines;
    Semaphore mutex = new Semaphore(1);
    AtomicInteger i = new AtomicInteger(0);
    int index;

    @Override
    public void run() {

        long actual = 0;
        try {
            Calculate calculate = new Calculate();
            long multiStart = System.currentTimeMillis();

            Thread first = new Thread(calculate);
            Thread second = new Thread(calculate);
            Thread third = new Thread(calculate);

            first.start();
            second.start(); 
            third.start();

            first.join();
            second.join();
            third.join();

            long multiEnd = System.currentTimeMillis();
            actual = multiEnd - multiStart;

        } catch (InterruptedException ex) {
            Logger.getLogger(MultiThread.class.getName()).log(Level.SEVERE, null, ex);
        }

        int sum = 0;
        for (Map.Entry<String, AtomicInteger> entry : asciiMap.entrySet()) {
            System.out.println("Char: " + entry.getKey() + " , number: " + entry.getValue());
            sum = sum + entry.getValue().get();
        }

        System.out.println("Time: " + actual);

    }

    int increment() {

        try {
            mutex.acquire();
            index = i.incrementAndGet();
            mutex.release();

        } catch (InterruptedException ex) {
            Logger.getLogger(MultiThread.class.getName()).log(Level.SEVERE, null, ex);
        }
        return index;
    }

    public class Calculate implements Runnable {

        public Calculate() {
        }

        @Override
        public void run() {

            while (i.get() < asciiLines.size()) {
                for (String oneCharacter : asciiLines.get(i.get()).split("")) {
                    if (asciiMap.containsKey(oneCharacter)) {
                        asciiMap.replace(oneCharacter, new AtomicInteger(asciiMap.get(oneCharacter).incrementAndGet()));
                    } else {
                        asciiMap.put(oneCharacter, new AtomicInteger(1));
                    }
                }
                i = new AtomicInteger(increment());
            }
        }
    }

}

LinkedList中的每个元素都包含一行(1 000个字符)。

1 个答案:

答案 0 :(得分:4)

您的代码绝对没有多线程。 Thread.join表示等待该线程执行完毕,然后继续当前的执行线程。现在,您的代码正在以串行方式执行每个线程。您希望将您的呼叫交错到开始和加入。

Thread first = new Thread(calculate);
Thread third = new Thread(calculate);
Thread second = new Thread(calculate);

first.start();
second.start();
third.start();

first.join();
second.join();
third.join();