【发布时间】:2017-09-27 20:44:10
【问题描述】:
我想使用 ExecutorService 打印所有字符串排列,但与在单线程上运行相比并不快。
我的代码:
private static void setUpThreads(String startCharacter, char inputLength[], String withoutStartChar, int threadnumber) {
ExecutorService exec = Executors.newFixedThreadPool(threadnumber);
exec.execute(() -> permutation(startCharacter, inputLength, 0, withoutStartChar));
exec.shutdown();
try {
exec.awaitTermination(600, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Threadnumber 可以是 1 或 8,结果在我的计算机上是一样的。 我用 Startchar 对其进行了测试:a inpuLength: 17 withoutStartCharacter : sdf 结果将是相同的:135 秒 我的电脑:i7-6700HQ,8 GB 内存(4 核 8 线程)
还有排列码:
private static void permutation(String startCharacters, char[] maxLength, int pos, String input) {
if (pos == maxLength.length) {
if (leRepetation(maxLength))
System.out.println(startCharacters + new String(maxLength));
} else {
for (int i = 0; i < inputSize; i++) {
maxLength[pos] = input.charAt(i);
permutation(startCharacters, maxLength, pos + 1, input);
}
}
}
我可以通过多线程以某种方式加快进程吗?或者有什么其他方法可以加快速度?
【问题讨论】:
-
没有多线程的速度是多少?秒?分钟?
-
没有 ExecutorService 135 秒,使用 ExecutorService 135 秒(8 线程)
-
您知道您只提交了一项任务,对吧?因此,执行程序中的所有其他线程都只是闲置。
-
但是您只创建了一个无论如何都在一个线程中执行的任务。为什么您认为时间会有所不同?
-
我明白了。我可以用多线程加速这个任务吗?
标签: java string algorithm permutation