Java:如何将多线程实现为递归文件夹大小查找器算法?

时间:2018-06-11 17:12:05

标签: java multithreading parallel-processing

所以,我已经开发了文件夹大小查找器的单线程版本,但是为了使它更有趣,我想提高它的速度,并希望培养我对多线程进程的理解。然而,在大约30次修改后,似乎总是存在问题,无论是否:   - 主线程在所有线程完成之前打印结果   - 当它不应该(可能有双重计数)时,长型溢出   - 多线程版本需要比单线程版本更长的时间

我不知所措,我不知道这样的问题是不适合多线程还是我错了。我已经把我最成功的'修订如下。

我意识到它从技术上开始然后立即加入工作线程,使其几乎比单步行更差。然而,这是我获得主线程以显示正确结果的唯一方法。

所以我的主要问题是让工作线程只在最后加入,使它并行浏览所有子文件夹,然后加入主线程以显示正确的结果。

package sizeBrowserCode;

import java.io.File;
import java.io.FileWriter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


public class Main {
static long lengthy;
static Thread worker;
static long sum;

private static long getLength() {
    return Main.lengthy;
}

private static void setLength(long var) {
    Main.lengthy=var;
}

private static long getFolderSize(File folder) {
    long length=0;
    File[] files = folder.listFiles();

    int count = files.length;

    for (int i = 0; i < count; i++) {
        if (files[i].isFile()) {
            length += files[i].length();
        }
        else {
            length += getFolderSize(files[i],true);
        }
    }
    System.out.println(folder+" // "+length);

    return length;
}

private static long getFolderSize(File folder,boolean multiThreaded) {
    if(multiThreaded) {
        long length;
        worker=new Thread(new Runnable() {
             public void run() {

                setLength(getFolderSize(folder));
                 }
                });
            worker.start();
            try {
                worker.join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            length=getLength();
        return length;

    }else {
        return getFolderSize(folder);
    }
}


public static String convert_Bytes(long bytes,String prefered_Unit) {
    prefered_Unit=prefered_Unit.toLowerCase().trim();
    switch (prefered_Unit) {
    case "b": return (bytes+" Bytes");
    case "kb": return (bytes/1024+" Kilobytes");
    case "mb": return (bytes/Math.pow(1024,2)+" Megabytes");
    case "gb": return (bytes/Math.pow(1024,3)+" Gigabytes");
    case "tb": return (bytes/Math.pow(1024,4)+" Terabytes");
    default:System.out.println("Incorrect notation; Please use\nb\nkb\nmb\ngb\ntb");
            System.exit(0);
            return null;

    }
}

public static String convert_Bytes(long bytes) {
    double Kb=0;
    double Mb=0;
    double Gb=0;
    double Tb=0;
    String result;
    if (bytes>=1024) {
        Kb=bytes/1024;
        bytes=0;
        result=" Kilobytes";
        if(Kb>=1024) {
            Mb=Kb/1024;
            Kb=0;
            result=" Megabytes";
            if(Mb>=1024) {
                Gb=Mb/1024;
                Mb=0;
                result=" Gigabytes";
                if(Gb>=1024) {
                    Tb=Gb/1024;
                    Gb=0;
                    result=" Terabyte";
                }
            }
        }
    }else {
        result=" Bytes";
    }
    double sum=bytes+Mb+Gb+Tb;
    return (sum+result);
}

public static void main(String[] args) {

    String chosen_Folder =args[0];
    String prefered_Unit;
    String full_Size;
    try {
        prefered_Unit =args[1];
    }catch (Exception e) {
        prefered_Unit=null;
    }

    String local_Folder=System.getProperty("user.dir");
    File full_Path;
    String backslash   ="\\";
    String forwardslash="/";
    String seperater;
    if(System.getProperty("os.name").toLowerCase().indexOf("win")>=0) {
        seperater=backslash;
    }else {
        seperater=forwardslash;
    }
    full_Path=new File(local_Folder+seperater+chosen_Folder);



    System.out.println(full_Path);
    long startTime =System.nanoTime();
    if(prefered_Unit!=null) {
        full_Size=convert_Bytes(getFolderSize(full_Path),prefered_Unit);

    }else {
        full_Size=convert_Bytes(getFolderSize(full_Path));
    }
    long endTime =System.nanoTime();

    System.out.println("The size of "+chosen_Folder+" is: "+full_Size);
    System.out.println("Took "+TimeUnit.NANOSECONDS.toSeconds(endTime-startTime)+" seconds to execute.");
    File size_Indicator = new File(full_Path+seperater+"FileSize.txt");
    try {
    size_Indicator.createNewFile();
    FileWriter writer = new FileWriter(size_Indicator);
    writer.write(full_Size);
    writer.close();
    }catch(Exception e) {
        System.err.println(e);
    }

}

}

1 个答案:

答案 0 :(得分:1)

只是为了补充其他答案。

尽量避免使用

worker = new Thread(new Runnable() {
    ...
  }

改为使用Executor。它们更易于使用,安排,运行和恢复结果。此外,他们负责线程池和其他开销。

阅读this

自Java 5以来,执行程序可用,它们是任何JVM的组成部分。