我有一个小型暴力破解器的以下代码部分。我一直在尝试学习多线程,并且我有不会停止的执行程序。
private void generateThreads(int cores){
if (cores > Runtime.getRuntime().availableProcessors() || cores <= 0)
cores = Runtime.getRuntime().availableProcessors();
ArrayList<Future<?>> tasks = new ArrayList<Future<?>>(cores);
ExecutorService executor = Executors.newFixedThreadPool(cores);
final long step = 2000;
for (long i = 0; i < Long.MAX_VALUE; i += step){
while(tasks.size() > cores) {
for(int w = 0; w < tasks.size();w++){
if(tasks.get(w).isDone()){
tasks.remove(w);
break;
}
}
try{
Thread.sleep(0);
}
catch (InterruptedException e){
e.printStackTrace();
}
}
{
if (passwordFound == false){
tasks.add(executor.submit(new Runnable(){
public void run(){
String attempt;
while(true){
try {
Thread.sleep(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
attempt = bf.toString();
bf.increment();
if (passwordCrack(attempt)){
crackedPassword.append(attempt);
passwordFound = true;
break;
}
}
}
}));
}
else
break;
}
}
executor.shutdownNow();
}
我认为 Thread.sleep(0) 将使线程能够捕获 InterruptedException,但我的线程继续永远存在。我能做些什么来确保一旦找到密码,线程就会正确停止?