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

Java 为什么这个多线程代码没有更快?,java,multithreading,performance,Java,Multithreading,Performance,这是我的java代码。以前,它按顺序调用BatchGenerateResult,这是一个漫长的过程,但我想尝试一些多线程处理,并让它们同时运行。但是当我测试它时,新的时间和旧的时间是一样的。我希望新的时间会更快。有人知道怎么了吗 public class PlutoMake { public static String classDir; public static void main(String[] args) throws JSONException, IOException,

这是我的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;
  }
}

您好,很抱歉无法添加到评论部分,因为刚刚加入

建议您首先使用虚拟方法,检查它是否在您的终端工作,然后添加您的业务逻辑。。。 如果示例有效,那么您可能需要检查模板类 这是样品。。检查时间戳

 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();
            }
        }

    }

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

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—我怀疑您在这方面能实现多大的性能改进


做一个概要文件,检查每个方法执行的时间。这取决于您应该能够理解。

您的机器有多少CPU内核?尝试System.out.printlnRuntime.getRuntime.availableProcessors;它打印什么?2个CPU 4个线程,英特尔i3代1@sneaky,请尝试Executors.newFixedThreadPoolRuntime.getRuntime.availableProcessors;现在检查性能。还有你有多少文件?len变量的值是什么?可能是在MyJSON、Exporter类中有同步方法吗?此示例与此代码无关。如果你回答了几个你知道如何回答的问题,你就可以对这个问题发表评论。@durron。。检查基本功能,然后添加业务逻辑,这不是一条基本规则吗?不过,这并不能回答问题。调试提示不是答案。