多线程与单线程比较

àì夳堔傛蜴生んèń 2024-04-01 18:59 231阅读 0赞

给一个多行的txt文本文件,统计里面每个单词出现多少次(如下图)

52db7d2ec63e411998b5b08344fb1e71.png

单线程代码:

  1. import java.io.BufferedReader;
  2. import java.io.FileNotFoundException;
  3. import java.io.FileReader;
  4. import java.io.IOException;
  5. import java.util.TreeMap;
  6. public class TestDemo {
  7. public static void main(String[] args) {
  8. FileReader fr = null;
  9. BufferedReader br = null;
  10. TreeMap<String, Integer> worldMap = new TreeMap<String, Integer>();
  11. long start = System.currentTimeMillis();
  12. try {
  13. fr = new FileReader("fos.txt");
  14. br = new BufferedReader(fr);
  15. String temp = "";
  16. int num = 0;//读取行数
  17. while ((temp = br.readLine()) != null) {
  18. num++;
  19. String[] splitStr = temp.trim().split(" ");
  20. for (int i = 0; i < splitStr.length; i++) {
  21. if (worldMap.containsKey(splitStr[i])) {//原Map中包含key
  22. Integer count = worldMap.get(splitStr[i]) + 1;
  23. worldMap.put(splitStr[i], count);
  24. } else {
  25. //原map中不包含这个key(单词)
  26. worldMap.put(splitStr[i], 1);
  27. // System.out.println("不包含");
  28. }
  29. }
  30. }
  31. System.out.println("读取文件总行数:" + num);
  32. for (String key : worldMap.keySet()) {
  33. Integer wordNum = worldMap.get(key);
  34. System.out.println(key + "出现的次数为:" + wordNum);
  35. }
  36. long totalTime = System.currentTimeMillis() - start;
  37. System.out.println("程序运行时间:" + totalTime);
  38. } catch (FileNotFoundException e) {
  39. e.printStackTrace();
  40. } catch (IOException e) {
  41. e.printStackTrace();
  42. } finally {
  43. try {
  44. br.close();
  45. fr.close();
  46. } catch (IOException e) {
  47. e.printStackTrace();
  48. }
  49. }
  50. }
  51. }

运行结果:

1a86be64a64c48358a1c91b971dc2121.png

多线程代码:

  1. import java.util.HashMap;
  2. import java.util.Map;
  3. public class wordCount implements Runnable {
  4. String content = "";
  5. Map<String, Integer> map = new HashMap<>();
  6. public wordCount(String content) {
  7. this.content = content;
  8. }
  9. @Override
  10. public void run() {
  11. String[] split = content.trim().split(" ");
  12. for (int i = 0; i < split.length; i++) {
  13. if (map.containsKey(split[i])){
  14. Integer value = map.get(split[i]) + 1;
  15. map.put(split[i],value);
  16. }else {
  17. map.put(split[i],1);
  18. }
  19. }
  20. }
  21. }
  22. import java.io.BufferedReader;
  23. import java.io.FileNotFoundException;
  24. import java.io.FileReader;
  25. import java.io.IOException;
  26. import java.util.HashMap;
  27. import java.util.Iterator;
  28. import java.util.Map;
  29. import java.util.Set;
  30. import java.util.concurrent.ExecutorService;
  31. import java.util.concurrent.Executors;
  32. public class wordCountTest {
  33. static Map<String, Map<String, Integer>> threadMAP = new HashMap<>();
  34. public static void main(String[] args) {
  35. long start = System.currentTimeMillis();
  36. FileReader fr = null;
  37. BufferedReader bf = null;
  38. int lineNum = 0;
  39. ExecutorService executorService = Executors.newCachedThreadPool();
  40. try {
  41. fr = new FileReader("fos.txt");
  42. bf = new BufferedReader(fr);
  43. StringBuffer listStrBuf = new StringBuffer("");
  44. String lineStr = "";
  45. // boolean tag = true;
  46. while ((lineStr = bf.readLine()) != null) {
  47. listStrBuf.append(lineStr + " ");
  48. lineNum++;
  49. if (lineNum % 100000 == 0) {
  50. wordCount wordCount = new wordCount(listStrBuf.toString());
  51. listStrBuf.delete(0, listStrBuf.length());
  52. Thread thread = new Thread(wordCount);
  53. // thread.start();
  54. executorService.execute(thread);
  55. threadMAP.put("thread-" + lineNum / 100000, wordCount.map);
  56. }
  57. }
  58. if (listStrBuf.toString().length() > 0) {
  59. wordCount wordCount = new wordCount(listStrBuf.toString());
  60. Thread thread = new Thread(wordCount);
  61. executorService.execute(thread);
  62. threadMAP.put("thread-last", wordCount.map);
  63. }
  64. System.out.println("文件总行数为:" + lineNum);
  65. executorService.shutdown();
  66. while (true) {
  67. if (executorService.isTerminated()) {
  68. Map<String, Integer> mapResult = new HashMap<>();
  69. // for (Map<String, Integer> tempMap : threadMAP.values()) {
  70. // System.out.println(tempMap.keySet());
  71. // }
  72. for (String key : //thread-1 thread-2 ....... thread-last
  73. threadMAP.keySet()) {
  74. Map<String, Integer> perThreadWorldNum = threadMAP.get(key);
  75. Set<String> perThreadWords = perThreadWorldNum.keySet();
  76. Iterator<String> iterator = perThreadWords.iterator();
  77. while (iterator.hasNext()) {
  78. String word = iterator.next();
  79. if (mapResult.containsKey(word)) {
  80. Integer wordsNum = perThreadWorldNum.get(word);
  81. Integer haveNum = mapResult.get(word);
  82. mapResult.put(word, wordsNum + haveNum);
  83. } else {
  84. mapResult.put(word, perThreadWorldNum.get(word));
  85. }
  86. }
  87. /*
  88. System.out.println(key);
  89. System.out.println(threadMAP.get(key).keySet());
  90. for (String word :
  91. threadMAP.get(key).keySet()) {
  92. System.out.print(word + ":" + threadMAP.get(key).get(word) + " ");
  93. }
  94. System.out.println();*/
  95. }
  96. Set<String> resultWords = mapResult.keySet();
  97. for (String word : resultWords) {
  98. System.out.println(word + " : " + mapResult.get(word));
  99. }
  100. break;
  101. }
  102. }
  103. } catch (FileNotFoundException e) {
  104. e.printStackTrace();
  105. } catch (IOException e) {
  106. e.printStackTrace();
  107. } finally {
  108. try {
  109. fr.close();
  110. bf.close();
  111. } catch (IOException e) {
  112. e.printStackTrace();
  113. }
  114. }
  115. long endTime = System.currentTimeMillis() - start;
  116. System.out.println("程序运行时长:" + endTime + "ms");
  117. }

运行结果:

51bea5c50bcb45dab880dd756245e152.png

总结:

两次运行结果比较:TXT文件总行数33082行,单线程运行时间39ms,多线程运行时间45ms

后面又测试了一个595476行的txt文件,单线程运行时间208ms,多线程运行时间182ms

所以说,并不是多线程运行的时间一定会比单线程运行的时间短。

但是,当文件比较大的时候多线程的优势就体现出来了。

单线程和多线程在选用的时候要看具体需求。

发表评论

表情:
评论列表 (有 0 条评论,231人围观)

还没有评论,来说两句吧...

相关阅读

    相关 线单线速度

    多线程不一定比单线程速度快,只有在特定的场景下,多线程才能发挥优势。 例如数据库的存储,单线程速度就比多线程快。 多线程适用于复杂任务,并发任务,往往响应需要一定的时间,这