Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.FileWriter;
- import java.util.ArrayList;
- public class ThreadRunner {
- static class TestThread implements Runnable {
- private int threadNumber = 0;
- private int nFiles = 0;
- public void run() {
- for (int f = 0; f < nFiles; f++) {
- String fileName = outputFolder + "multi" + (threadNumber * nFiles + f) + ".txt";
- try {
- FileWriter fw = new FileWriter(fileName, false);
- for (long j = 0; j < numLines; j++) {
- fw.write(outStr);
- }
- fw.close();
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- }
- public TestThread(int num, int nFiles) {
- threadNumber = num;
- this.nFiles = nFiles;
- }
- }
- private static int numFiles = 60;
- private static int numThreads;
- private static final long numLines = 2000000;
- private static final String outStr = "123456789\r\n";
- private static final String outputFolder = "./dummyStuff";
- public static void multithread() throws InterruptedException {
- ArrayList<Thread> threads = new ArrayList<Thread>();
- for (int i = 0; i < numThreads; i++) {
- threads.add(new Thread(new TestThread(i, numFiles / numThreads)));
- threads.get(threads.size() - 1).start();
- }
- for (int i = 0; i < numThreads; i++) {
- threads.get(i).join();
- }
- }
- public static void singlethread() throws InterruptedException {
- for (int i = 0; i < numFiles; i++) {
- String fileName = outputFolder + "single" + i + ".txt";
- try {
- FileWriter fw = new FileWriter(fileName, false);
- // Write a lot of stuff
- for (long j = 0; j < numLines; j++) {
- fw.write(outStr);
- }
- fw.close();
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- }
- public static void main(String[] args) throws InterruptedException {
- for (numThreads = 1; numThreads <= 6; numThreads++) {
- long startTime = System.currentTimeMillis();
- multithread();
- // System.out.println("Multithreaded: " +
- // (System.currentTimeMillis() - startTime));
- long startTime2 = System.currentTimeMillis();
- singlethread();
- // System.out.println("Singlethreaded: " +
- // (System.currentTimeMillis() - startTime));
- System.out.println(
- numThreads + ": " + (startTime2 - startTime) + " vs. " + (System.currentTimeMillis() - startTime2));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement