2013-05-05 201 views
0

我有這樣的代碼:Java多線程停止所有其他線程立即

public class BruteForceThread implements Callable<String> { 

private static volatile boolean stopped = false;   

public String call() { 

    String password = this.getNextPassword(); 

    while (!stopped) { 

     System.out.println(numberOfThreat + ": " + password); 

     synchronized(this) { 
      try { 
       if (this.testPassword(password)) { 
        stopped = true; 
        return password; 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

     password = this.getNextPassword(); 

    } 
    return ""; 

} 
} 

主要類:

public static void main(String[] args) throws IOException { 

int numberOfThreads = 2; 
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads); 
CompletionService<String> pool = new ExecutorCompletionService<String>(executor); 
for (int i = 1; i < numberOfThreads + 1; i++) { 
    Callable<String> bruteForce = new BruteForceThread(...); 
    pool.submit(bruteForce); 
} 

executor.shutdown(); 

    for(int i = 0; i < numberOfThreads; i++){ 
     try { 
      String result = pool.take().get(); 
      if (result != "") { 
       System.out.println("Your password: " + result); 
      } 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } catch (ExecutionException e) { 
      e.printStackTrace(); 
     } 
    } 

executor = null; 
} 

輸出: ...

1: aa <- here first thread found a password 
2: Fa <- second thread is continue 
2: Fb 
2: Fc 
... many more ... 
2: IZ 
Your password: aa 

如果一個線程找到密碼和設置停止爲true,另一個線程不會立即停止。爲什麼?

+0

你有多少核心? – didierc 2013-05-05 08:44:08

+0

您可以嘗試使用AtomicBoolean而不是 – MadProgrammer 2013-05-05 08:45:26

+0

我使用了'ArrayBlockingQueue'作爲字符串的來源,並且我無法重現該問題。儘管我的系統只有一個內核 – didierc 2013-05-05 11:16:46

回答

0

會有等待寫入控制檯的線程。這意味着當您檢查停止時以及輸出到屏幕時,可能會有一些或所有線程位於這兩個線程之間。

順便說一句,除非你以高延遲方式攻擊一個網站,否則你可能會發現破解密碼只能使用與CPU一樣多的線程。更多的線程可能會增加開銷並減慢開銷。