java - 线程排序比非线程排序运行得慢

标签 java multithreading sorting java-threads

我正在尝试使用线程对文件进行排序。这是 Sort.java:

这个函数在线程的帮助下排序

public static String[] threadedSort(File[] files) throws IOException {
      String sortedData[] = new String[0]; 
      int counter = 0; 
      boolean allThreadsTerminated = false;
      SortingThread[] threadList = new SortingThread[files.length];
      for (File file : files) {
          String[] data = getData(file);
          threadList[counter] = new SortingThread(data);
          threadList[counter].start();
          counter++;
      }
      while(!allThreadsTerminated) {
          allThreadsTerminated = true;
          for(counter=0; counter<files.length; counter++) {
              if(threadList[counter].getState() != Thread.State.TERMINATED) {
                  allThreadsTerminated = false;               
              }           
          }
      }
      for(counter=0; counter<files.length; counter++) {
          sortedData = MergeSort.merge(sortedData, threadList[counter].data);
      }
      return sortedData;
 }

这个函数正常排序

  public static String[] sort(File[] files) throws IOException {
    String[] sortedData = new String[0];
    for (File file : files) {
      String[] data = getData(file);
      data = MergeSort.mergeSort(data);
      sortedData = MergeSort.merge(sortedData, data);
    }
    return sortedData;
  }

现在,当我使用两种方式进行排序时,正常排序比线程版本更快。可能是什么原因呢?我错过了什么吗?

我的 SortingThread 是这样的:

public class SortingThread extends Thread {
    String[] data;
    SortingThread(String[] data) {
        this.data = data;
    }
    public void run() {
         data = MergeSort.mergeSort(data);        
    }  
}

当我通过比较线程实现与原始非线程实现的性能来分析我的线程实现时,我发现第二个更快。这种行为的原因是什么?如果我们谈论相对性能改进,如果没有错的话,我们预计线程实现会更快。

编辑:假设我有正常运行的 MergeSort。但是在这里发布它的代码是没有用的。 getData() 函数也只是从文件中获取输入。 我认为问题在于将整个文件放入数组中这一事实。我想我应该为不同的线程提供不同的行:

private static String[] getData(File file) throws IOException {
    ArrayList<String> data = new ArrayList<String>();
    BufferedReader in = new BufferedReader(new FileReader(file));
    while (true) {
      String line = in.readLine();
      if (line == null) {
        break;
      }
      else {
        data.add(line);
      }
    }


    in.close();
    return data.toArray(new String[0]);
  }

最佳答案

首先,您如何测量耗时?您是否在同一个程序中执行这两个测试?如果是这样,请记住,合并排序可能会在执行第一个测试时进行 Hotspot 编译。我建议你每个方法运行两次,测量第二次运行的时间

关于java - 线程排序比非线程排序运行得慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30690987/

相关文章:

c# - TextBlock 不会更新

python - 按 Python 中元组的第一个元素自然地对字母数字元组列表进行排序

java - 当recyclerview的itemview进入屏幕区域时如何更新firebase中的子值?

java.lang.reflect.InaccessibleObjectException : Unable to make field private final transient java.net.InetSocketAddress

java - 如何使用 Eclipse Lyo 获取 IBM RTC 中的工作项?

ios - Objective-C - 终止在后台运行的所有其他应用程序

java - 序列化和反序列化未实现 java.io.Serializable 的对象

安卓 | RecyclerView 不起作用

python-3.x - 如何在python 3中按本地语言对拉丁语进行排序?

c++ - 为什么我们将 greater<string>() 传递给排序算法?