Java Multithread立即停止所有其他线程

时间:2013-05-05 08:20:01

标签: java multithreading executorservice completion-service

我有这段代码:

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

如果一个线程找到密码并将stopped设置为true,则另一个线程不会立即停止。为什么呢?

1 个答案:

答案 0 :(得分:0)

将有线程等待写入控制台。这意味着当你检查停止和输出到屏幕时,部分或全部线程可能介于两者之间。

BTW除非您正在以高延迟攻击网站,否则您可能会发现破解密码只需要与拥有CPU的线程一样多。更多线程可能会增加开销并降低速度。