简体   繁体   English

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

[英]Java Multithread stopping all other threads immediately

I have this code: 我有以下代码:

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 "";

}
}

Main class: 主班:

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;
}

Output: ... 输出:...

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

If one thread find a password and sets stopped to true, another threads does not stop immediately. 如果一个线程找到密码并将其设置为true,则另一个线程不会立即停止。 Why? 为什么?

There will be threads waiting to write to the console. 将有等待写入控制台的线程。 This means some or all the threads could be between when you check for stopped and when you output to the screen. 这意味着某些线程或所有线程都可能在检查停止状态和输出到屏幕之间。

BTW Unless you are hacking a web site with a high latency you might find that cracking a password is done with only as many threads as you have CPUs. 顺便说一句,除非您以高等待时间入侵网站,否则您可能会发现破解密码仅使用与CPU数量相同的线程来完成。 More threads could add overhead and slow it down. 更多线程可能会增加开销并减慢它的速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM