The code is essentially correct. The problem seems to be in the initialization parameters. If, as for your example, the correct password (finalCorrect
), starts with NH
then inside list initials
there must be the value NH
.
As for stopping the working threads once the solution is found, you can call executorService.shutdownNow()
to attempt to stop the threads. Inside the loop you will have to check for the interrupted status.
Here is an adaptation of your code with a bit more logging, that stops the working threads:
ExecutorService executorService= Executors.newFixedThreadPool(30);
for(String x : inicials){
System.out.println("Checking " + x);
executorService.submit(()->{
for(int count=0;count<999999; count++){
if(finalCorrect.equals(x+String.format("%06d", count).trim())){
System.out.println("Correct password is: "+x+String.format("%06d", count).trim());
System.out.println("The really password is: "+ finalCorrect);
// Attempt to stop all the threads...
executorService.shutdownNow();
break;
}
// Test if the thread has been requested to stop
if (Thread.currentThread().isInterrupted()) {
System.out.println("Interrupted " + x);
return;
}
}
System.out.println("End " + x);
}
);
}
executorService.shutdown();
try {
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException x) {
System.out.println(x);
}
Using the new Streams features of Java 8, you could implement the same aPproach with a more compact form:
inicials.parallelStream()
.flatMap(x -> IntStream.rangeClosed(0, 999999).mapToObj(i -> x + String.format("%06d", i)))
.filter(finalCorrect::equals)
.findAny()
.ifPresent(x -> System.out.println("Found correct password: " + x));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…