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 に答える