为什么这个多线程代码更快?

时间:2015-08-17 04:21:41

标签: java multithreading performance

这是我的java代码。之前,它按顺序调用BatchGenerateResult,这是一个漫长的过程,但我想尝试一些多线程并让它们中的每一个同时运行。但是当我测试它时,新时间与旧时间相同。我预计新时间会更快。有谁知道什么是错的?

public class PlutoMake {

  public static String classDir;

  public static void main(String[] args) throws JSONException, IOException,
      InterruptedException {

    // determine path to the class file, I will use it as current directory
    String classDirFile = PlutoMake.class.getResource("PlutoMake.class")
        .getPath();
    classDir = classDirFile.substring(0, classDirFile.lastIndexOf("/") + 1);

    // get the input arguments
    final String logoPath;
    final String filename;
    if (args.length < 2) {
      logoPath = classDir + "tests/android.png";
      filename = "result.png";
    } else {
      logoPath = args[0];
      filename = args[1];
    }

    // make sure the logo image exists
    File logofile = new File(logoPath);
    if (!logofile.exists() || logofile.isDirectory()) {
      System.exit(1);
    }

    // get the master.js file
    String text = readFile(classDir + "master.js");
    JSONArray files = new JSONArray(text);

    ExecutorService es = Executors.newCachedThreadPool();

    // loop through all active templates
    int len = files.length();
    for (int i = 0; i < len; i += 1) {
      final JSONObject template = files.getJSONObject(i);
      if (template.getBoolean("active")) {
        es.execute(new Runnable() {
          @Override
          public void run() {
            try {
              BatchGenerateResult(logoPath, template.getString("template"),
                  template.getString("mapping"),
                  template.getString("metadata"), template.getString("result")
                      + filename, template.getString("filter"),
                  template.getString("mask"), template.getInt("x"),
                  template.getInt("y"), template.getInt("w"),
                  template.getInt("h"));
            } catch (IOException | JSONException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          }
        });
      }
    }

    es.shutdown();
    boolean finshed = es.awaitTermination(2, TimeUnit.MINUTES);
  }

  private static void BatchGenerateResult(String logoPath, String templatePath,
      String mappingPath, String metadataPath, String resultPath,
      String filter, String maskPath, int x, int y, int w, int h)
      throws IOException, JSONException {
    ColorFilter filterobj = null;
    if (filter.equals("none")) {
      filterobj = new NoFilter();
    } else if (filter.equals("darken")) {
      filterobj = new Darken();
    } else if (filter.equals("vividlight")) {
      filterobj = new VividLight();
    } else {
      System.exit(1);
    }

    String text = readFile(classDir + metadataPath);
    JSONObject metadata = new JSONObject(text);

    Map<Point, Point> mapping = MyJSON.ReadMapping(classDir + mappingPath);

    BufferedImage warpedimage = Exporter.GenerateWarpedLogo(logoPath, maskPath,
        mapping, metadata.getInt("width"), metadata.getInt("height"));
    // ImageIO.write(warpedimage, "png", new FileOutputStream(classDir +
    // "warpedlogo.png"));

    Exporter.StampLogo(templatePath, resultPath, x, y, w, h, warpedimage,
        filterobj);

    warpedimage.flush();
  }

  private static String readFile(String path) throws IOException {
    File file = new File(path);
    FileInputStream fis = new FileInputStream(file);
    byte[] data = new byte[(int) file.length()];
    fis.read(data);
    fis.close();
    String text = new String(data, "UTF-8");
    return text;
  }
}

2 个答案:

答案 0 :(得分:0)

看起来,出于所有实际目的,以下代码应该是唯一可以通过使用多线程来提高性能的代码。

BufferedImage warpedimage = Exporter.GenerateWarpedLogo(logoPath, maskPath,
    mapping, metadata.getInt("width"), metadata.getInt("height"));
// ImageIO.write(warpedimage, "png", new FileOutputStream(classDir +
// "warpedlogo.png"));

Exporter.StampLogo(templatePath, resultPath, x, y, w, h, warpedimage,
    filterobj);

其余主要IO - 我怀疑你可以在那里实现多少性能提升。

执行配置文件并检查每个方法执行的时间。取决于你应该能够理解的。

答案 1 :(得分:-1)

对不起,刚刚加入评论部分就不能添加..

会建议首先使用虚拟方法检查它是否适用于您的最终然后添加您的业务逻辑... 如果样本有效,那么您可能需要检查“模板”类 这是样本..检查时间戳

 package example;

    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;

    public class ExecutorStaticExample {


        public static void main(String[] args){
            ExecutorService  ex = Executors.newCachedThreadPool();
            for (int i=0;i<10;i++){
                    ex.execute(new Runnable(){

                        @Override
                        public void run() {
                            helloStatic();
                            System.out.println(System.currentTimeMillis());

                        }

                    });
            }
        }

        static void helloStatic(){
            System.out.println("hello form static");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }