Advertisement
Nickpips

Untitled

May 18th, 2016
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. import java.io.FileWriter;
  2. import java.util.ArrayList;
  3.  
  4. public class ThreadRunner {
  5.  
  6. static class TestThread implements Runnable {
  7.  
  8. private int threadNumber = 0;
  9. private int nFiles = 0;
  10.  
  11. public void run() {
  12. for (int f = 0; f < nFiles; f++) {
  13. String fileName = outputFolder + "multi" + (threadNumber * nFiles + f) + ".txt";
  14. try {
  15. FileWriter fw = new FileWriter(fileName, false);
  16.  
  17. for (long j = 0; j < numLines; j++) {
  18. fw.write(outStr);
  19. }
  20. fw.close();
  21. } catch (Exception ex) {
  22. ex.printStackTrace();
  23. }
  24. }
  25.  
  26. }
  27.  
  28. public TestThread(int num, int nFiles) {
  29. threadNumber = num;
  30. this.nFiles = nFiles;
  31. }
  32.  
  33. }
  34.  
  35. private static int numFiles = 60;
  36.  
  37. private static int numThreads;
  38.  
  39. private static final long numLines = 2000000;
  40. private static final String outStr = "123456789\r\n";
  41. private static final String outputFolder = "./dummyStuff";
  42.  
  43. public static void multithread() throws InterruptedException {
  44. ArrayList<Thread> threads = new ArrayList<Thread>();
  45. for (int i = 0; i < numThreads; i++) {
  46. threads.add(new Thread(new TestThread(i, numFiles / numThreads)));
  47. threads.get(threads.size() - 1).start();
  48. }
  49. for (int i = 0; i < numThreads; i++) {
  50. threads.get(i).join();
  51. }
  52. }
  53.  
  54. public static void singlethread() throws InterruptedException {
  55. for (int i = 0; i < numFiles; i++) {
  56. String fileName = outputFolder + "single" + i + ".txt";
  57. try {
  58. FileWriter fw = new FileWriter(fileName, false);
  59. // Write a lot of stuff
  60. for (long j = 0; j < numLines; j++) {
  61. fw.write(outStr);
  62. }
  63. fw.close();
  64. } catch (Exception ex) {
  65. ex.printStackTrace();
  66. }
  67. }
  68. }
  69.  
  70. public static void main(String[] args) throws InterruptedException {
  71. for (numThreads = 1; numThreads <= 6; numThreads++) {
  72. long startTime = System.currentTimeMillis();
  73. multithread();
  74. // System.out.println("Multithreaded: " +
  75. // (System.currentTimeMillis() - startTime));
  76. long startTime2 = System.currentTimeMillis();
  77. singlethread();
  78. // System.out.println("Singlethreaded: " +
  79. // (System.currentTimeMillis() - startTime));
  80.  
  81. System.out.println(
  82. numThreads + ": " + (startTime2 - startTime) + " vs. " + (System.currentTimeMillis() - startTime2));
  83. }
  84.  
  85. }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement