0

我有一个小型暴力破解器的以下代码部分。我一直在尝试学习多线程,并且我有不会停止的执行程序。

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,但我的线程继续永远存在。我能做些什么来确保一旦找到密码,线程就会正确停止?

4

2 回答 2

2

您还必须检查passwordFound变量:

// inside your run() method
while(!Thread.currentThread().isInterrupted() && !passwordFound) {
  ...
}

Thread.sleep()据我所知,不需要。

PS更正了我的答案,以使其更清楚我的意思。

于 2012-12-11T16:11:04.567 回答
1

看来您想要这样的行为:

public void run() {
  /* do something */
  while(!passwordFound) {
      /* do something */
  }      
} 

小心锁定存储密码的变量!

于 2012-12-11T16:13:54.167 回答