繁体   English   中英

Java:使用 ExecutorService 进行并发

[英]Java: Using ExecutorService for concurrency

我想并行执行一些任务,所以我在 Java 中搜索多线程,我找到了这个类,ExecutorService。 我尝试了一个简单的例子,但我不确定它是否并行运行。

long startTime = System.currentTimeMillis();
List<Callable<String>> callables = new ArrayList<Callable<String>>();
ExecutorService executor = Executors.newCachedThreadPool();
callables.add(new Callable<String>() {
        public String call() {
            for (int i=0; i<100000; i++) {
                System.out.println("i "+i);
            }
            return "Task 1";
        }
    }
);
        
callables.add(new Callable<String>() {
        public String call() {
            for (int j=0; j<100000; j++) {
                System.out.println("j "+j);
            }
            return "Task 2";
        }
    }
);
        
callables.add(new Callable<String>() {
     public String call() {
          for (int k=0; k<100000; k++) {
              System.out.println("k "+k);
          } 
          return "Task 3";
      }
  }
);
try {
    List<Future<String>> futureLst = executor.invokeAll(callables);
    for (Future future : futureLst) {
        try {
            System.out.println(future.get());
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
executor.shutdown();
System.out.println("Time Taken - "+ (System.currentTimeMillis() - startTime));

上面的代码按预期工作正常并打印计数并返回字符串。 上述程序执行所需的时间为“3229”毫秒。

我把上面的程序改写如下,

long startTime = System.currentTimeMillis();
for (int i=0; i<100000; i++) {
    System.out.println("i "+i);
}
for (int j=0; j<100000; j++) {
    System.out.println("j "+j);
}
for (int k=0; k<100000; k++) {
    System.out.println("k "+k);
}
System.out.println("Time Taken - "+ (System.currentTimeMillis() - startTime));

这个程序花费的时间是“3104”毫秒,比并行执行编码的时间少。

那么我在第一个程序中做错了什么吗? 我的第一个程序是否并行运行任务,因为我看到没有线程花费的时间更少?

第一个是顺序的,第二个是并行的——这很好。

看起来运行时间主要由System.out.println调用中缓慢的控制台写入操作组成(请参阅为什么 System.out.println 这么慢? )。

如果您改为写入文件,您应该观察不同的行为(和并行版本加速)。

您的任务主要是使用System.out.println调用(即PrintStream.println方法)写入标准输出。 它最终调用PrintStream.write方法,其中主体已同步。 因此,您只是将时间浪费在创建线程和同步开销上。 由于PrintStream本质上是顺序的,它不能并行输出,所以当单个流正在写入时,其他人只是在等待它。 某些操作可以像 for 循环和字符串和数字的连接一样并行化,但它们比输出到 stdout 快得多。

为了从并发中获得额外的性能,您应该避免使用共享的顺序资源。 在您的情况下,它是标准输出流。

你的代码是正确的。 结果是由于计算太简单,运行速度太快。 大部分运行时间由控制台输出的速度决定,因此多线程的好处并不能弥补设置和关闭线程池的开销。 此外,try-catch 设置还增加了一个小的开销(非常小,但足以在这个简单的场景中纠结结果)。 --> 您可以尝试增加循环大小(提示:使用静态变量 MAX_LOOP 进行更快的测试),您将看到不同之处。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM