我想用 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,内存8GB(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);
}
}
}
我可以通过多线程以某种方式加快进程吗?或者任何其他加快速度的方法?
最佳答案
这看起来很适合 ForkJoinPool .在一个任务中,您可以跨多个线程 fork 出各种子任务,我认为这是您的意图。
关于Java 字符串置换ExecutorService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46456922/