我有以下一段代碼用於小型暴力破解程序。我一直在努力學習多線程,並且我有執行者不會停下來。如何在java中阻止我的線程
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的能力,但是我的線程會一直持續下去。我能做些什麼來確保一旦找到密碼,線程就能正確地停止?
我通常只使用布爾標誌。當你想停止時,將其設置爲false。 – MikeTheLiar
這是你在找什麼? http://stackoverflow.com/questions/671049/how-do-you-kill-a-thread-in-java –