如何在java中停止我的线程

时间:2012-12-11 16:05:40

标签: java multithreading

我有一个小型暴力代码的以下代码段。我一直在努力学习多线程,我有执行者不会停止。

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

2 个答案:

答案 0 :(得分:2)

您还必须检查passwordFound变量:

// inside your run() method
while(!Thread.currentThread().isInterrupted() && !passwordFound) {
  ...
}
据我所见,

Thread.sleep()不需要。

P.S。纠正了我的回答,以便更明确我的意思。

答案 1 :(得分:1)

您似乎想要这样的行为:

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

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